代码之家  ›  专栏  ›  技术社区  ›  justiceorjustus

Javascript中异步递归函数块内部是否有同步函数调用?

  •  0
  • justiceorjustus  · 技术社区  · 5 月前

    将异步 bar() 等待同步 foo() 在等待新的promise/timeout和调用之前完成 bar() 再一次?

    function foo() {
        console.log('is bar waiting for me to finish?');
    }
    
    async function bar() {
        foo(); // is this blocking?
        await new Promise((r) => setTimeout(r, 10));
        await bar();
    }
    
    bar();
    
    2 回复  |  直到 5 月前
        1
  •  2
  •   KLASANGUI    5 月前

    简短的回答是“ “我的意思是, foo() 哪个同步将被阻止 bar() 执行至 foo() 完成。但是,作为 bar() 是异步的,那么 foo() 不会阻止外部代码 bar() .

    const delay = 3000; // 3 seconds of delay.
    
    function foo() {
        console.log('Is bar waiting for me to finish?');
        console.log('Answer: Yes!');
    }
    
    async function bar() {
        await new Promise((r) => setTimeout(r, delay)); // waits `delay` and `foo()`.
        foo(); // is this blocking? r: yes
        await new Promise((r) => setTimeout(r, delay)); // waits `delay` and loop.
        await bar(); // loops.
    }
    
    // Will not block the lines that follows:
    bar();
    
    // Unblocked line.
    console.log('I am not blocked by `bar()`.');
        2
  •  0
  •   TheTanadu    5 月前

    对, foo() 将在等待电话之前完成 bar() . foo() JavaScript执行在同步函数中逐行进行。wait关键字只会暂停async函数内的执行 bar() 之后 foo() 已经完成了。

    您可以通过添加(模拟)一些延迟来验证这一点。

    function foo() {
        console.log('is bar waiting for me to finish?');
        let start = Date.now();
        while (Date.now() - start < 5000) {} // Simulate delay
        console.log('foo finished');
    }
    
    async function bar() {
        console.log('calling foo');
        foo();
        console.log('foo returned');
        await new Promise((r) => setTimeout(r, 10));
        console.log('timeout finished');
        // Preventing infinite recursion, just for testing
        //await bar();
    }
    
    bar();