【问题标题】:async and Q promises in nodejsnodejs 中的异步和 Q 承诺
【发布时间】:2014-01-04 06:55:13
【问题描述】:

我在 nodejs 中使用Q 库和async 库。

这是我的代码示例:

async.each(items, cb, function(item) {

 saveItem.then(function(doc) {
    cb();
 });

}, function() {

});

saveItem 是一个承诺。当我运行它时,我总是得到cb is undefined,我猜then() 没有访问权限。任何想法如何解决这个问题?

【问题讨论】:

    标签: node.js asynchronous q node-async


    【解决方案1】:

    你的问题不在于承诺,而在于你对async的使用。

    async.each(items, handler, finalCallback)handler 应用于items 数组的每个项目。 handler 函数是异步的,即它收到一个回调,它必须在完成工作时调用它。当所有处理程序都完成后,将调用最终回调。

    以下是解决当前问题的方法:

    var handler = function (item, cb) {
      saveItem(item)
      .then(
        function () { // all is well!
            cb();
        },
        function (err) { // something bad happened!
            cb(err);
        }
      );
    }
    
    var finalCallback = function (err, results) {
      // ...
    }
    
    async.each(items, handler, finalCallback);
    

    但是,对于这段特定的代码,您不需要使用 async:仅 Promise 就可以很好地完成这项工作,尤其是使用 Q.all()

    // Create an array of promises
    var promises = items.map(saveItem);
    
    // Wait for all promises to be resolved
    Q.all(promises)
    .then(
        function () { // all is well!
            cb();
        },
        function (err) { // something bad happened!
            cb(err);
        }
    )
    

    【讨论】:

    • 你提到了Q.all解决方案
    • 热代码。肯定会用它来获得乐趣和利润。 :)
    猜你喜欢
    • 1970-01-01
    • 2018-11-03
    • 2019-06-21
    • 1970-01-01
    • 2015-05-12
    • 2018-08-26
    • 2015-02-04
    • 2018-07-01
    • 2016-09-12
    相关资源
    最近更新 更多