2014-04-06 31 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