0

I'm just learning backend programming with Node, and very new to how asynchronous programming works. A problem requires me to get data from an array of urls, and return the data in the order they were listed. I used a for loop to get and return the data, essentially looking something like this:

for(let i=0;i<urlArray.length;i++){
    http.get(urlArray[i],(response)=>{
        //return the response 
    }
}

How do I do this?

Geuis
  • 41,122
  • 56
  • 157
  • 219
albert
  • 1,158
  • 3
  • 15
  • 35
  • 1
    have you read the difference between `let` and `var` ... it's to do with the **scope** of the variable - important when dealing with asynchronous code, for each iteration, the *value* of variable `i` "frozen" in the block if you like, there's probably a better way to explain that, but the fact that you don't understand the documentation you've read make it difficult - though not at all important in the code you've shown – Jaromanda X Feb 15 '18 at 04:03
  • Ok, `var`, `let`, and `const` don't have anything to do with your problem. The differences between them have to do with variable scope. What you need to look into are Promises. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – Geuis Feb 15 '18 at 04:06
  • https://technology.amis.nl/2017/05/18/sequential-asynchronous-calls-in-node-js-using-callbacks-async-and-es6-promises/ – Janaka Dissanayake Feb 15 '18 at 04:21
  • 1
    Promises + Promise.all – Ayush Gupta Feb 15 '18 at 04:21
  • https://stackoverflow.com/questions/38426745/how-do-i-return-the-accumulated-results-of-multiple-parallel-asynchronous-func this might help you – Janaka Dissanayake Feb 15 '18 at 04:27

1 Answers1

0

It is quite simple(and cleaner) if you use bluebird promises as they support the Promise.map functionality.

const bbPromise = require('bluebird');

return bbPromise.map([...(new Array(urlArray.length))], (item, idx) => {
    return new bbPromise(resolve => {
        http.get(urlArray[idx], (response) => {
            resolve(response);
        });
    });
});
Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92