0

nodejs multiple http requests in loop

As per the above question,it was answered how to perform a loop of http requests with an array of urls which works fine.But what I am trying to achieve is to perform another loop of http requests which should be done only after the completion of the first loop (i.e) it should wait for the first loop of http requests to complete.

// Import http
var http = require('http');

// First URLs array
var urls_first = ["http://www.google.com", "http://www.example.com"];

// Second URLs array
var urls_second = ["http://www.yahoo.com", "http://www.fb.com"];

var responses = [];
var completed_requests = 0;

function performHTTP(array) {
for (i in urls_first) {
        http.get(urls[i], function(res) {
            responses.push(res);
            completed_requests++;
            if (completed_requests == urls.length) {
                // All download done, process responses array
                console.log(responses);
            }
        });
    }
 }

In the above snippet ,i have added another array of urls.I wrapped the for inside a function to change the array each time called.Since i have to wait for the first loop to complete, i tried async/await like below.

async function callMethod() { 
    await new Promise (resolve =>performHTTP(urls_first)))   // Executing function with first array
    await new Promise (resolve =>performHTTP(urls_second)))  // Executing function with second array
} 

But in this case both the function calls get executed simultaneously(i.e)it does not wait for the first array execution to complete .Both execution happens simultaneously,which i need to happen only after the completion of one.

2
  • You can use promise, callback, async await or eachSeries, async library. I prefer : caolan.github.io/async/v3/docs.html#eachSeries Commented Sep 18, 2019 at 6:28
  • what i believe is await will wait for any previous await to complete.Since i want several loops ,to callback would be complex.Instead i even tried using .then which didnt work either like ` var promise1 = await new Promise (resolve =>performHTTP(urls_first)) promise1.then(await new Promise (resolve =>performHTTP(urls_second)))` Commented Sep 18, 2019 at 6:34

3 Answers 3

2

You need to make your request inside a Promise :

function request(url) {
    return new Promise((resolve, reject) => {
       http.get(url, function(res) {
        // ... your code here ... //
        // when your work is done, call resolve to make your promise done
         resolve()
       });
    }
}

And then resolve all your requests

// Batch all your firts request in parallel and wainting for all
await Promise.all(urls_first.map(url => request(url)));
// Do the same this second url
await Promise.all(urls_second.map(url => request(url)));

Note, this code is not tested and may contains some mistake, but the main principle is here.

More information about Promise : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise

Sign up to request clarification or add additional context in comments.

1 Comment

tried this ,only the first await works ,it does not goto second await
0

Check out how to use .then() to call second performHttp right after the first one is completed.

1 Comment

calling the function inside .then does not work for me.
0

You can call services using eachSeries.

https://www.npmjs.com/package/async-series

series([
  function(done) {
    console.log('First API Call here')
    done() // if you will pass err in callback it will be caught in error section.
  },
  function(done) {
    console.log('second API call here')
    done()
  },
  function(done) {
    // handle success here
  }
], function(err) {
  console.log(err.message) // "another thing"
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.