【问题标题】:Simple flow control in NodeJsNodeJs 中的简单流控制
【发布时间】:2014-04-06 19:30:58
【问题描述】:

我已经阅读了许多示例和教程,尽管我知道解决方案可能很简单,但我就是无法理解它。非常感谢这里的任何帮助。

我在 Node.js 中有两个函数。 functionA() 不接受任何参数并返回一个英文字符串。第二个,functionB(english) 获取从 funcitonA() 返回的英文字符串并将其翻译成另一种语言。

我相信回调是这里最好的解决方案,但对于我来说,我无法弄清楚最好的结构是什么。

提前致谢。

【问题讨论】:

  • 你到底想做什么? functionA 应该如何被调用?这是你认为回调会有所帮助的地方,还是关于 A-->B 调用?
  • 真的,我不确定。我真正想要的是在 functionA 返回后调用 functionB 的可靠方法。
  • functionA 是异步的吗?

标签: node.js controls flow


【解决方案1】:

我有点不清楚您要做什么(您可能想多了),但请考虑以下内容,它说明了这些函数被调用和相互调用的四种方式。作为澄清,我应该注意我不是在编写节点样式的回调,它总是采用 callback(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);
    });
});

还要注意,还有其他方法可以处理异步操作,例如使用 Promise(我自己更喜欢 Q Promise 库,但还有其他选择)。但是,在将抽象覆盖在它之上之前,可能值得了解核心行为。

【讨论】:

  • 太好了,是的,我可能想多了。消息和翻译都是对外部 API 的异步调用。让我试试你的最后一个例子,然后再报告。谢谢!
  • 哦,如果它们都是异步调用,你可能不会想太多。是的,最后一个示例通常是您想要遵循的。随着您对嵌套回调的深入了解,其他抽象(例如 Promise 或异步库)将值得学习,以使事情看起来不那么复杂。
  • 我遇到这个问题的代码在这里; github.com/briantwalter/nodejs-ycf/blob/master/ycf.js 它们都是异步的,我特别想避免你提到的抽象,因为我想先学习如何使用基础知识。我还是有点迷茫,但我会继续努力。
  • 我必须做几件事情,但今晚晚些时候可以对您的代码进行一些更正。但是你需要更多的回调。您的 catfact = yodaspeak(function getcatfact()); 没有为您做任何有用的事情。您将希望在传递给 getcatfact 的回调中调用 yodaspeak。反过来,yodaspeak 将需要接受/使用回调,而该回调将负责调用 res.render。以后有需要的话。否则,如果您整理好了,请留下便条。
  • @briantwalter - 请参阅 this gist 以获取适用于调用样式的代码的更新版本。我不想重新创建您的项目以进行全面测试,但如果所有 API 都正常工作,这应该可以正常工作。我已经通过包含我姓名缩写 BFJ 的评论记录了我的所有更改。
猜你喜欢
  • 2012-07-29
  • 2020-08-10
  • 2015-04-30
  • 1970-01-01
  • 2011-05-07
  • 2011-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多