SAlidadi SAlidadi - 1 year ago 33
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

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

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

Answer Source

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... */) {