0

I have this code:

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

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

So I want iterate an array of urls, and for each url I want call the promiseFunction that make some fetch and computing using the Bluebird promise library, my question is how can I wait the response of the promise before continuing the iteration with the next element? I have Node JS 6.10.0 and at the moment I can't switch version so I can't use the async/await API. Someone can help me?

After Svenskunganka response, i update my question with his answer:

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

If you test it, you can see that print immediatly: Started url1 Started url2 Started url3

So doesn't wait, I think the answer isn't correct or I haven't understand it

Someones have closed this question because it was considered duplicated, ma it's different to the question linked as duplicate, anyway I found a solution for my problem, if anyone needed:

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 
Piero
  • 9,173
  • 18
  • 90
  • 160

0 Answers0