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

断了今生、忘了曾经 提交于 2019-12-25 07:27:58

问题


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...
    )};
 });

回答1:


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);


来源:https://stackoverflow.com/questions/38670458/how-i-can-iterate-over-an-array-and-pass-items-to-a-method-also-all-methods-shou

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!