javascript - .every() not waiting for HTTP request -
this question has answer here:
i running http request using popular node-request module each item in array; running function @ last item of array. code goes this:
const request = require('request'); var arr = ['john', 'jane', 'marry', 'scarlet']; var x = 0; arr.every(function (i) { x++; /*instead of waiting request, adds x , moves on making x 3 when first request runs*/ request({ url: 'http://localhost:8810/getlastname?firstname=' + }, function (error, response, body) { //execute code if(x==arr.length){ //therefore function run each item in array. // should run once per array. } }) return true; })
i hoping achieve without writing ton of code therefore keeping code nice , neat.
edit: i'm not trying run in order. don't mind running in parallel i'm trying trigger function once on completion.
instead of using variable x
, use second argument every
local every
call function:
arr.every(function (i, j) { // ... if (j+1==arr.length) ...
while variable x
common iterations, each iteration has own version of j
, since declared within callback closure. therefore not give issue experiencing x
.
Comments
Post a Comment