Javascript forEach循环中的Subscribe调用执行得太晚

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

为什么控制台日志在末尾显示所有“if”输出

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
数组将按您不期望的顺序排列