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

等待执行的顺序在节点中没有意义

  •  1
  • user2741831  · 技术社区  · 1 年前

    我想知道异步js函数是在何时被附加到事件循环的,以及何时被立即执行:

    async function test2(){
        console.log('3 test2 is being executed');
    }
    async function test(){
        console.log('2 test is being executed');
    
        await test2();
        console.log('4 test 2 was awaited');
    }
    
    console.log('1 test is about to be called');
    test();
    console.log('5 test was called');
    

    最初,我假设无论一个函数是否有任何实际的异步函数(setTimeout、fetch、loadFile等)发生,如果该函数被声明为异步,它总是会被附加到事件循环中。

    因此,根据该逻辑,控制台日志的顺序如下:

    1 test is about to be called
    5 test was called
    2 test is being executed
    3 test2 is being executed
    4 test 2 was awaited
    

    所以我假设,没有任何实际异步函数的异步函数总是会立即执行,导致以下顺序:

    1 test is about to be called
    2 test is being executed
    3 test2 is being executed
    4 test 2 was awaited
    5 test was called
    

    但我得到的却是:

    1 test is about to be called
    2 test is being executed
    3 test2 is being executed
    5 test was called
    4 test 2 was awaited
    

    这意味着执行顺序为:

    测试被调用 测试正在立即执行(尽管标记为异步) test2正在立即执行(与test相同) 在运行test2之后,控制权返回到第14行(这意味着事件循环一定做了什么) 最后,测试报告test2已执行。

    有人能给我解释一下吗?为什么异步函数有时会被抛出到事件循环中,有时则不会?我这是可以预测的,什么时候?

    此外,如果您删除wait,则顺序为1 2 3 4 5。

    我只是想知道这里的逻辑是什么。

    编辑: 如果wait关键字是关键,为什么这会导致相同的执行顺序?

    async function test2(){
        console.log('3 test2 is being executed');
    }
    async function test(){
        console.log('2 test is being executed');
    
        await test2();
        console.log('4 test 2 was awaited');
    }
    
    console.log('1 test is about to be called');
    let a=async ()=>{
        await test();
    }
    a();
    console.log('5 test was called');
    
    
    1 test is about to be called
    2 test is being executed
    3 test2 is being executed
    5 test was called
    4 test 2 was awaited
    
    1 回复  |  直到 1 年前
        1
  •  2
  •   Jonas Wilms    1 年前

    async 函数始终同步执行,直到第一个 await 。当等待的Promise解决时,执行继续。一 async 函数总是返回一个Promise,即使没有 等待 里面。即使一个Promise resolve(…) d同时,它的结算总是推迟到一个作业。

    在这两个示例中,异步事件都是通过从返回创建的隐式Promise的结算 test2 test .