在我的 Sails.js 应用程序初始化期间,我需要执行多项任务,其中一项任务与另一项任务相关。如果这些任务中的任何一个返回错误,则整个链应该失败并取消sails lift
。
伪代码:
configureApis()
.then(getServiceStatus)
.then(setRegionJobs)
.then(cb)
.catch(cb)
问题是,这些函数都返回 Promises(cb
除外,它是回调函数 in this question 。
我怎样才能实现这个目标? async.waterfall
这里有什么用处吗?
最佳答案
如果将任何函数包装在 Promise 构造函数中,都可以成为 Promise。就像:
...
.then(function(){ return somePromise(); })
.then(function(){
return Promise(function(resolve, reject){
/* do whatever your function here, and call either resolve or reject
* resolve usually for `positive` or true result
* reject usually for `negative` or false result, and it's usually an Error object
*/
someFunction('param1', callback function(err, result){
if (err) return reject(err);
return resolve(result);
});
});
})
.then(function(result){
/* result from previous Promise can be use here */
})
.catch(function(err){
/* catch error from any of promises above */
console.error(err);
});
关于javascript - 在 Node.js 和 sails.js 中链接异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32186945/