无法在数组中保存异步操作结果



我在forEach循环中调用网络请求,每个请求都返回一个新对象,我想将其推送到forEach外部的数组中。当它在等待网络请求完成后被调用时,它返回为空";[]";。

return this.get(urlOne, function (error, response) {
if (response.statusCode === 200) {
let array = [];
stores.forEach((store) => {
this.get(urlTwo, function (error, response) {
if (response.statusCode === 200) {
array.push(response.body);
}
});
});
console.log(array);
}
});

这只是猜测,但是stores.for每个内容都是异步的,因此console.log(数组(在stores之后立即调用。forEach((被调用d(未完成(,意味着数组为空。console.log(数组(;可能需要在请求实际完成时调用。

测试这是否属实的最简单方法是查看每次推送的数组。如果您看到数组随着数据的增长而增长,则存在问题。

return this.get(urlOne, function (error, response) {
if (response.statusCode === 200) {
let array = [];
stores.forEach((store) => {
this.get(urlTwo, function (error, response) {
if (response.statusCode === 200) {
array.push(response.body);
console.log(array);
}
});
});
}
});

(编辑(

if (response.statusCode === 200) 
array.push(response.body);
else if(response.statusCode === 204)
console.log(array);

状态代码204表示无内容,如果这不是自动发送的或等效的,您可能需要手动发送。

最新更新