Bluebird mapSeries

一曲冷凌霜 提交于 2019-12-09 16:41:21

问题


I am trying to execute a series of promises in order, only going to the next one after the previous is resolved. From Bluebird docs:

The iterator won't be called for an item until its previous item, and the promise returned by the iterator for that item are fulfilled. http://bluebirdjs.com/docs/api/promise.mapseries.html

var Promise = require('bluebird');


function test(time) {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            console.log(time);
            resolve(time);
        }, time);
    });
}

Promise.mapSeries([test(2000), test(1000), test(500), test(3000)], function(a) {
    return a;
}).then(function(results) {
    console.log(results);
});

What I expect is that the console.log inside the test function to show: 2000, 1000, 500, 3000 in that order. I expect that because as the docs states, each item goes only after the previous is resolved. Instead, I get 500, 1000, 2000, 3000, which reflects that all the functions are called instanstaneously. Moreover, results does show the results in the order they were called, though that is irrelevant at this point.

Am I misunderstanding something here?


回答1:


Your test calls are being before Promise.mapSeries ever gets a chance to run. Also mapSeries is normally run on a promise instance. Maybe the following example helps to understand? Note how test(time) this time returns a function.

function test(time) {
    return function(value) {
      return new Promise(function(resolve, reject) {
          setTimeout(function() {
              console.log('time', time);
              resolve(time);
          }, time);
      });
    };
}

Promise.resolve([test(2000), test(400), test(1000), test(1), test(5000)])
       .mapSeries(function(asyncMethodPassed) {
                    return asyncMethodPassed();
}).then(function(results) {
    console.log('result', results);
});


来源:https://stackoverflow.com/questions/42582747/bluebird-mapseries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!