0

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) {
    x++;
    /*instead of waiting for request, it adds x and moves on making x
    3 when the first request finally runs*/
    request({
        url: 'http://localhost:8810/getLastName?firstName=' + i
    }, function (error, response, body) {
        //execute some code
        if(x==arr.length){ 
            //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.

EDIT: I'm not trying to run it in order. I don't mind it running in parallel but I'm just trying to trigger a function once on completion.

Monstrum
  • 88
  • 15
  • You should use promises. http://blog.slaks.net/2015-06-10/advanced-promise-usage/ – SLaks Nov 13 '16 at 00:46
  • `request()` is async. It doesn't block. You have to write your code using promises or callbacks that keep track of when every async operation is done. Do you want to serialize the requests (one at a time) or run them all in parallel and just know when they are all done? – jfriend00 Nov 13 '16 at 00:49
  • I just want to know when its all done so I can run that last function once. – Monstrum Nov 13 '16 at 00:49
  • [How can I wait for set of asynchronous callback functions?](http://stackoverflow.com/questions/10004112/how-can-i-wait-for-set-of-asynchronous-callback-functions/10004137#10004137) – jfriend00 Nov 13 '16 at 00:50
  • Ill give it a shot. – Monstrum Nov 13 '16 at 00:52
  • @WaseemI. - So. The fact that the array is of unknown length has nothing to do with anything. You can see the length at any time with `.length`. – jfriend00 Nov 13 '16 at 00:52

1 Answers1

0

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.

trincot
  • 317,000
  • 35
  • 244
  • 286