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.forEach,但这使得调用异步,我也应该在每次响应后做一些事情并需要同步调用。做这个的最好方式是什么?
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 个解决方案
#1
1
You could use Array.prototype.slice()
, Array.prototype.shift()
to return results in sequential order corresponding to input array
您可以使用Array.prototype.slice(),Array.prototype.shift()以与输入数组对应的顺序返回结果
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);
#1
1
You could use Array.prototype.slice()
, Array.prototype.shift()
to return results in sequential order corresponding to input array
您可以使用Array.prototype.slice(),Array.prototype.shift()以与输入数组对应的顺序返回结果
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);