SAlidadi SAlidadi - 4 months ago 8
Node.js Question

How I can iterate over an array and pass items to a method also all methods should run synchronously?

I want to call a request method that gets the body of itself as an array that is also one item of another array. so I should iterate over this parent array and pass its items to request method for a new request to server.
I have used

bodies.forEach
but this make the calls
async
and I should also do something after every response and need
sync
calls. What is the best way to do this?



bodies = [ [['name', 'Saeid'], ['age','23']],
[['name', 'Saeid'], ['age', 23 ], ['city', 'Tehran']]
]
bodies.forEach(function(body){
request(body, function(res){
//do something with this response and if meet oure desired condition continue...
)};
});




Answer

You could use Array.prototype.slice(), Array.prototype.shift() to return results in sequential order corresponding to input array

bodies = [ [['name', 'Saeid'], ['age','23']],
           [['name', 'Saeid'], ['age', 23 ], ['city', 'Tehran']]
          ];

var copy = bodies.slice(0);
var results = [];

function queue(arr) { 
  let curr = arr.shift();
  request(curr, (res) => {
    // do stuff with `res`
    // results.push(res);
    if (arr.length /* && if meet oure desired condition continue... */) {
      queue(arr)
    }
  })
}

queue(copy);
Comments