我如何迭代数组并将项传递给方法也是所有方法应该同步运行? [英] How I can iterate over an array and pass items to a method also all methods should run synchronously?

查看:98
本文介绍了我如何迭代数组并将项传递给方法也是所有方法应该同步运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用一个请求方法,该方法将自身的主体作为一个数组获取,该数组也是另一个数组的一个项目。所以我应该迭代这个父数组并将其项目传递给请求方法以获取对服务器的新请求。
我使用过 bodies.forEach 但是这会调用 async 而且我每次都应该做点什么响应和需要同步来电。最好的方法是什么?

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

推荐答案

您可以使用 Array.prototype。 slice() Array.prototype.shift()以对应于输入数组的顺序返回结果

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

这篇关于我如何迭代数组并将项传递给方法也是所有方法应该同步运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆