Javascript forEach循环中的Subscribe调用执行得太晚
为什么控制台日志在末尾显示所有“if”输出Javascript forEach循环中的Subscribe调用执行得太晚,javascript,if-statement,foreach,Javascript,If Statement,Foreach,为什么控制台日志在末尾显示所有“if”输出 3要素: 其他的 要素: 其他的 要素: 其他的 要素: 其他的 2要素: 4如果 我期望输出: elem 如果 元素 其他的 我以为它会在每个“元素”后面显示“如果”或“否则” 代码如下: res.docs.forEach((elem) => { console.log('elem'); if (elem.productType) { this.Service.function(elem.productTyp
3要素:
其他的
要素:
其他的
要素:
其他的
要素:
其他的
2要素:
4如果
我期望输出:
elem
如果
元素
其他的
我以为它会在每个“元素”后面显示“如果”或“否则”
代码如下:
res.docs.forEach((elem) => {
console.log('elem');
if (elem.productType) {
this.Service.function(elem.productType._id).subscribe((result) => {
console.log('if');
const text = result.name;
this.marketPlaceList.push(text);
});
} else {
console.log('else');
this.marketPlaceList.push('');
}
});
当一个可观察对象异步发出事件时,您的
forEach
循环将在执行对.subscribe
的任何回调之前完成
您可以通过将可观察对象转化为承诺,然后等待它来解决这个问题。要使wait
工作,您需要一个async
函数,因此将代码包装到这样一个函数中,并将forEach
循环更改为For
循环:
(async () => { // Async wrapper
for (const elem of res.docs) { // Use for-loop
console.log('elem');
if (elem.productType) {
// Convert observable to promise, and await
const result = await this.Service.function(elem.productType._id).toPromise();
console.log('if');
const text = result.name;
this.marketPlaceList.push(text);
} else {
console.log('else');
this.marketPlaceList.push('');
}
}
)(); // execute immediately
当您需要完全填充
this.marketPlaceList
数组时,请确保等待最外层的async
函数(或在其上使用然后)。完全取决于res.docs
的内容,但未在文章中显示。另外,如果服务是异步的。。。等待Service
是否有名为function
的方法?发布res.docs
中的内容。subscribe()
可能是一个异步函数您必须获取console.log('if')
退出异步响应,否则所有forEach
循环在开始记录它们时结束注意,您的this.marketPlaceList
数组将按您不期望的顺序排列