创建函数以正确链接承诺

Creating functions to chain promises correctly

我正在尝试让 Promise 链接正确地为我工作。

我认为问题归结为了解以下两者之间的区别:

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

和:

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

在这种情况下,我正在写 foobar 并试图使签名正确。 bar 确实采用 return 由 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');});
};

What is the difference between promise.then(foo).then(bar); and promise.then(foo.then(bar));?

第二个完全错误。 then 方法将回调作为其参数,而不是承诺。该回调可能 return 一个承诺,因此第一个相当于

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

(假设 foo return 也是一个承诺)。


您的整个代码似乎有点混乱。应该是

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);
    });
}