作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
<分区>
我是一名 API 开发人员,通常编写需要将结果从一个异步调用传递到另一个异步调用(也称为异步 waterfall )的端点。
我通常使用 promises 以下列方式执行此操作:
task1()
.then(result1){
task2(result1)
.then(result2){
task3(result2)
.then(result3){
// API response
})
.catch(function(err){
// Task 3 handle err
})
})
.catch(function(err){
// Task 2 handle err
})
})
.catch(function(err){
// Task 1 handle err
})
很明显,使用回调并没有带来太多好处。我现在得到的不是“回调 hell ”,而是“ promise hell ”。
我看过npm bluebird但似乎不支持 waterfall promise 。
有时我会使用 async并包装返回 promise 的任务:
const tasks = [
job1: function(cb){
task1()
.then(function(result){
cb(null, result);
})
.catch(function(err){
cb(err);
})
},
job2: function(cb, result1){
task2(result1)
.then(function(result){
cb(null, result);
})
.catch(function(err){
cb(err);
})
},
job3: function(cb, result2){
task3(result2)
.then(function(result){
cb(null, result);
})
.catch(function(err){
cb(err);
})
}
]
async.series(tasks, function(err, results){
if(err){
// handle error
}
// API callback
});
但这也没什么用。如果您正在考虑 Promise.all
,那是行不通的,因为一个任务的结果不会传递给下一个任务。
什么是更好的方法?
这个问题在这里已经有了答案: How to structure nested Promises (3 个答案) 关闭 6 年前。 我是一名 API 开发人员,通常编写需要将结果从一个异步调用传递到另
我是一名优秀的程序员,十分优秀!