创build函数以正确链接promise

我正在努力让Promise链接正确地为我工作。

我相信这个问题归结为理解之间的区别:

promise.then(foo).then(bar); 

和:

 promise.then(foo.then(bar)); 

在这种情况下,我正在写foobar并试图让签名正确。 bar确实是由foo产生的返回值。

我有后者的工作,但我的问题是我需要做些什么来得到前者的工作?

与上面相关的是完整的代码(如下)。 我没有按照期望的顺序打印不同的日志(期待log1log2log3log4log5 ,但获取log3log4log5log1log2 )。 我希望我能够像上面那样做,我也会得到这个工作的权利。

 var Promise = require('bluebird'); function listPages(queryUrl) { var promise = Promise.resolve(); promise = promise .then(parseFeed(queryUrl) .then(function (items) { items.forEach(function (item) { promise = promise.then(processItem(transform(item))) .then(function() { console.log('log1');}) .then(function() { console.log('log2');}); }); }).then(function() {console.log('log3')}) ).then(function() {console.log('log4')}) .catch(function (error) { console.log('error: ', error, error.stack); }); return promise.then(function() {console.log('log5');}); }; 

promise.then(foo).then(bar);之间的区别是什么? 并promise.then(foo.then(bar));

第二个是错的。 then方法将callback作为参数,而不是承诺。 这个callback可能会返回一个承诺,所以第一个相当于

 promise.then(function(x) { return foo(x).then(bar) }) 

(假设foo承诺)。


你的整个代码似乎有点搞砸了。 它应该可能阅读

 function listPages(queryUrl) { return parseFeed(queryUrl) .then(function (items) { var promise = Promise.resolve(); items.forEach(function (item) { promise = promise.then(function() { console.log('log1'); return processItem(transform(item)); }).then(function() { console.log('log2'); }); }); return promise; }).then(function() { console.log('log3') }, function (error) { console.log('error: ', error, error.stack); }); }