Zan*_*aes 6 callback node.js promise q
请原谅承诺的概念,请原谅我的新生儿.我在Node.js中使用Q模块.我有一个函数,一旦它执行了所有必要的步骤就打算调用它.当我想从Q promise中调用回调函数时,会出现问题.
我想要的功能是当我到达最后一步时能够调用回调,而不再是在承诺链中.因此,回调将回到其原始操作.但是,正如我编写的那样,回调在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();
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,回调函数中发生的错误会导致"OHNOES !!!!!" 要打印....
有一个方法,nodeify可以(可选)打破承诺链并转发到 NodeJS 风格的延续。
var updateDataStream = function(data, input, posts, stream, callback) {\n\n // Pack all the items up...\n return Q.ncall(data._packStream, data, posts, stream)\n // Upsert the cache into the database\n .then(function(){\n return Q.ncall(data.upsert, data);\n })\n // buffer the new input\n .then(function(res){\n return Q.ncall(data.buffer, data, input);\n })\n .nodeify(callback);\n\n}\nRun Code Online (Sandbox Code Playgroud)\n\n请注意在链的开头添加的“return”和在末尾添加的“nodeify(callback)”。
\n\n你的用户不需要知道你\xe2\x80\x99根本在使用Q\xe2\x80\xa6除非他们放弃回调,在这种情况下他们将得到一个承诺。
\n| 归档时间: |
|
| 查看次数: |
971 次 |
| 最近记录: |