如何在forEach中等待每次迭代调用Promise函数

时间:2018-04-17 15:18:17

标签: javascript node.js bluebird

我有这段代码:

var urls = ["url1","url2","url3"];
urls.forEach(function(url,i) {
promiseFunction(url)
}

function promiseFunction(string) {
    return new Promise(function(resolve, reject) {
        //Fetch
        //Compute
        resolve()
    });
}

所以我想迭代一个url数组,对于每个url,我想调用使用Bluebird promise库进行一些获取和计算的promiseFunction,我的问题是如何在继续迭代之前等待promise的响应下一个元素? 我有Node JS 6.10.0,目前我无法切换版本,所以我不能使用async / await API。 有人可以帮帮我吗?

在Svenskunganka回应之后,我用他的回答更新了我的问题:

var urls = [{name:"url1", delay: 1000},{name:"url2", delay: 5000},{name:"url3", delay: 3000}];

Promise.all(urls.map(promiseFunction)).then((results) => {
    console.log(results)
  }).catch((e) => {
    // Handle the error
  })

function promiseFunction(url) {
    return new Promise(function(resolve, reject) {
        console.log("Started "+url.name)
        setTimeout(
            function(){
                console.log(url.name+ " delay: "+url.delay)
                resolve(url.delay) 
        }, url.delay);
    });
}

如果您测试它,您可以立即看到该打印: 开始url1 开始url2 开始url3

所以不等,我认为答案不正确或者我不明白

有人已经关闭了这个问题,因为它被认为是重复的,与链接为重复的问题不同,无论如何我找到了解决我的问题的方法,如果有人需要:

var Promise = require("bluebird");

var urls = [{name:"url1", delay: 5000},{name:"url2", delay: 1000},{name:"url3", delay: 3000}];

var a = () => promiseFunction(urls[0]);
var b = () => promiseFunction(urls[1]);

function promiseFunction(url) {
    return new Promise(function(resolve, reject) {
        console.log("Started "+url.name)
        setTimeout(
            function(){
                console.log(url.name+ " delay: "+url.delay)
                resolve(url.delay) 
        }, url.delay);
    });
}

Promise.map([a, b], function (promiseFn) {
    return promiseFn(); //make sure that here You return Promise
}, {concurrency: 1}); //it will run promises sequentially 

0 个答案:

没有答案