简体   繁体   English

Promise Typescript 中的 forEach 内部

[英]Promise inside of forEach in Typescript

I have the following code:我有以下代码:

original_test(){
    var arr=[1,2,3]
    arr.forEach((a: any) => {
        console.log("Before")
        this.test().then(()=>{
            console.log("After")
        });
    });
}
test(){
    return new Promise((resolve) => {
        resolve(true)
    });
 }

My problem is that I want my code to wait for the next iteration of forEach (until the promise completes).我的问题是我希望我的代码等待 forEach 的下一次迭代(直到 promise 完成)。 That means I want as console output:这意味着我想要作为控制台 output:

"Before" “前”

"After" “后”

"Before" “前”

"After" “后”

"Before" “前”

"After" “后”

And what I get is:我得到的是:

"Before" “前”

"Before" “前”

"Before" “前”

"After" “后”

"After" “后”

"After" “后”

Many thanks!非常感谢!

I would do it like this:我会这样做:

async original_test() {
    var arr=[1, 2, 3];
    for(const item of arr) {
        console.log("Before")
        await this.test()
        console.log("After")
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM