Waseem I. Waseem I. - 1 year ago 66
Node.js Question

.every() not waiting for HTTP request

I am running an HTTP GET request using the popular node-request module for each item in an array; then running a function at the last item of the array. My code goes like this:

const request = require('request');
var arr = ['John', 'Jane', 'Marry', 'Scarlet'];
var x = 0;
arr.every(function (i) {
/*instead of waiting for request, it adds x and moves on making x
3 when the first request finally runs*/
url: 'http://localhost:8810/getLastName?firstName=' + i
}, function (error, response, body) {
//execute some code
//therefore this function is run for each item in the array.
// it should run only once per array.
return true;

I was hoping to achieve this without writing a ton of code therefore keeping my code nice and neat.

Answer Source

Instead of using the variable x, use the second argument to every which is local to the every call back function:

arr.every(function (i, j) {
 // ...

if (j+1==arr.length) ...

While the variable x is common to all iterations, each iteration has its own version of j, since it is declared within the callback closure. Therefore it will not give you the issue you are experiencing with x.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download