【问题标题】:Breaking out of a Q promise in Node.js when performing a callback?执行回调时打破 Node.js 中的 Q 承诺?
【发布时间】:2013-10-07 15:18:26
【问题描述】:

请原谅我对 Promise 概念的新手。 我在 Node.js 中使用 Q 模块。我有一个函数,一旦它执行了所有必要的步骤,它就会调用回调。当我想从 Q 承诺中调用回调函数时,就会出现问题。

我想要的功能是能够在我到达最后一步时调用回调,并且不再处于承诺链中。因此,回调将返回到其原始操作。然而,正如我编写的那样,回调在 promise 的上下文中被调用。此时,如果回调(比如说)抛出错误,它会被此函数中的错误处理程序捕获,这不是我想要的!

var updateDataStream = function(data, input, posts, stream, callback) {

    // Pack all the items up...
    Q.ncall(data._packStream, data, posts, stream)
    // Upsert the cache into the database
    .then(function(){
        return Q.ncall(data.upsert, data);
    })
    // buffer the new input
    .then(function(res){
        return Q.ncall(data.buffer, data, input);
    })
    .then(function(final){
        callback(null, final);
    })
    .fail(function(err){
        console.log('OHNOES!!!!!!!',err);
    }).end();
}

在这种情况下,回调函数中发生的错误会导致“OHNOES !!!!!”待打印……

【问题讨论】:

    标签: node.js callback promise q


    【解决方案1】:

    有一个方法,nodeify,它将(可选地)跳出承诺链并转发到 NodeJS 样式的延续。

    var updateDataStream = function(data, input, posts, stream, callback) {
    
        // Pack all the items up...
        return Q.ncall(data._packStream, data, posts, stream)
        // Upsert the cache into the database
        .then(function(){
            return Q.ncall(data.upsert, data);
        })
        // buffer the new input
        .then(function(res){
            return Q.ncall(data.buffer, data, input);
        })
        .nodeify(callback);
    
    }
    

    注意链开头添加的“return”和末尾添加的“nodeify(callback)”。

    你的用户根本不需要你使用 Q 更明智……除非他们放弃回调,在这种情况下他们会得到一个承诺。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-15
      • 2015-04-08
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 2014-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多