诺言瀑布
我是一个API开发人员,通常写端点需要从一个asynchronous调用结果传递到另一个asynchronous调用又名asynchronous瀑布。
我通常使用promise来做到这一点:
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 })
很明显,使用callback函数没有太多的收获。 现在我得到了“承诺地狱”,而不是“回拨地狱”。
我曾经看过npm蓝鸟,但是似乎没有支持瀑布的承诺。
有时我会使用asynchronous并包装的任务返回一个承诺:
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
,那么这将Promise.all
,因为一个任务的结果不会传递给下一个任务。
什么是更好的方法?
你有一个承诺反模式发生。 您可以从承诺中返回承诺,避免像您所做的那样嵌套承诺。
promiseOne() .then(() => promiseTwo()) .then(() => promiseThree()) .then(() => promiseFour());
顺便说一句,Node支持内置的Promise
构造函数。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
const promise = new Promise((resolve, reject) => { // do something and then resolve resolve(); }) promise().then(() => { ... });