In JavaScript, does using await inside a loop block the loop?

前端 未结 8 2551
南旧
南旧 2020-12-02 06:38

Take the following loop:

for(var i=0; i<100; ++i){
    let result = await some_slow_async_function();
    do_something_with_result();
}
8条回答
  •  佛祖请我去吃肉
    2020-12-02 07:12

    Here is my test solution about this interesting question:

    import crypto from "crypto";
    
    function diyCrypto() {
        return new Promise((resolve, reject) => {
            crypto.pbkdf2('secret', 'salt', 2000000, 64, 'sha512', (err, res) => {
                if (err) {
                    reject(err)
                    return 
                }
                resolve(res.toString("base64"))
            })
        })
    }
    
    setTimeout(async () => {
        console.log("before await...")
        const a = await diyCrypto();
        console.log("after await...", a)
    }, 0);
    
    setInterval(() => {
        console.log("test....")
    }, 200);
    

    Inside the setTimeout's callback the await blocks the execution. But the setInterval is keep runnning, so the Event Loop is running as usual.

提交回复
热议问题