2012-07-27 41 views
6

请原谅我的新信仰承诺的概念。 我在Node.js中使用Q模块。我有一个函数,一旦执行了所有必要的步骤,就会调用回调函数。当我想从Q promise中调用回调函数时会出现问题。在执行回调时突破Node.js中的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 !!!!!”将被打印....

回答

4

有一种方法,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的聪明......除非他们离开回调,在这种情况下他们会得到一个承诺。