2014-04-06 29 views
0

我已經閱讀了大量的示例和教程,雖然我知道解決方案可能很簡單,但我無法讓自己的大腦纏繞它。任何幫助在這裏將非常感激。NodeJs中的簡單流量控制

我在Node中有兩個函數。 functionA()不帶任何參數並返回一個英文字符串。第二個,函數B(英文)將從funcitonA()返回的英文字符串轉換爲另一種語言。

我相信回調是最好的解決方案,但在我的生活中,我無法弄清楚最好的結構是什麼。

在此先感謝。

+0

你究竟在做什麼?函數'應該如何被調用?這是您認爲回調會有幫助的地方,還是關於A - > B通話? –

+0

真的,我不確定。我真正想要的是在functionA返回後調用functionB的一種方法。 – briantwalter

+0

函數A是異步的嗎? –

回答

0

我對你想要做什麼(你可能會推翻事物)有點不清楚,但請考慮以下內容,它們說明了這些函數被調用和調用的四種方式。作爲一個澄清,我應該注意到,我沒有編寫節點樣式的回調函數,它總是採用形式回調(err,result),如果沒有錯誤,則err的計算結果爲false。你不必以這種方式編寫自己的回調,雖然我傾向於自己這樣做。

// your 'functionA' 
function getMessage(){ 
    return 'Hello'; 
}; 

// your 'functionB' 
function francofy(str) { 
    var result; 
    switch(str){ 
     case 'Hello': 
      result = 'Bon jour'; // 'Allo' might be better choice, but let's stick to node 
      break; 
     default: 
      throw new Error('My Vocabulary is too limited'); 
    } 
    return result; 
}; 

// the most straightforward use of these functions 

console.log('Synch message, synch translate', francofy(getMessage())); 

// what if the translation is asynch - for example, you're calling off to an API 
// let's simulate the API delay with setTimeout 
function contemplateTranslation(str,cb) { 
    setTimeout(function(){ 
     var result = francofy(str); 
     cb(result); 
    },1000); 
}; 

contemplateTranslation(getMessage(), function(translated){ 
    console.log('Synch Message, Asynch Translate: ' + translated); 
}); 

// what if the message is async? 
function getDelayedMessage(cb) { 
    setTimeout(function(){ 
     cb('Hello'); 
    },1000); 
}; 

getDelayedMessage(function(msg){ 
    console.log('Asynch Message, Synch Translate', francofy(msg)); 
}); 

// what if you need to call an asynchronous API to get your message and then 
// call another asynchronous API to translate it? 

getDelayedMessage(function(msg){ 
    contemplateTranslation(msg, function(translated){ 
     console.log("My God, it's full of callbacks", translated); 
    }); 
}); 

注意還存在其他的方法來處理異步操作,如與承諾(我更喜歡將q承諾庫自己,但也有其他的選擇)。但是,在覆蓋對它的抽象之前,可能值得理解核心行爲。

+0

這很好,是的,我可能正在想這個。消息和翻譯都是對外部API的異步調用。讓我試試你的最後一個例子,並將回報。謝謝! – briantwalter

+0

哦,如果他們都是異步調用,你可能不會超越它。是的,最後一個例子通常是你想要遵循的。隨着對嵌套回調的深入研究,其他抽象(例如承諾或異步庫)將值得學習,讓事情看起來不那麼複雜。 –

+0

我遇到這個問題的代碼是在這裏; https://github.com/briantwalter/nodejs-ycf/blob/master/ycf.js他們都是異步的,我特意試圖避免你提到的抽象,因爲我想先學習如何使用基礎知識。我仍然有點失落,但我會繼續黑客攻擊它。 – briantwalter