蓝鸟地图系列 [英] Bluebird mapSeries

查看:78
本文介绍了蓝鸟地图系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图按顺序执行一系列承诺,仅在解决前一个承诺之后才转到下一个承诺.来自Bluebird文档:

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:

直到它的上一个项目被调用,迭代器才被调用,并且迭代器为该项目返回的承诺得以实现. http://bluebirdjs.com/docs/api/promise.mapseries.html

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

我希望测试功能内的console.log显示如下:2000、1000、500、3000.我希望这是因为如文档所述,每个项目只有在解决前一个问题之后才能进行.相反,我得到500、1000、2000、3000,这反映了立即调用所有函数.而且,结果确实按调用的顺序显示了结果,尽管此时无关紧要.

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.

我在这里误会了吗?

推荐答案

您的测试调用是在 Promise.mapSeries 获得运行机会之前进行的.此外, mapSeries 通常也可以在promise实例上运行.也许以下示例有助于理解?请注意,这次 test(time)如何返回函数.

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

这篇关于蓝鸟地图系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆