zoukankan      html  css  js  c++  java
  • async/wait 多个async函数嵌套

    1. 假如函数

    async function A(){
      await customFun();  
      console.log("A");  
    }

    A()会等到customFun()的函数体内所有的代码执行结束,再执行console.log("A")。  

    async function customFun() {
        console.log("customFun")
        await new Promise((res,rej)=>{
            let t = 1000;
            setTimeout(()=>{
                console.log(`setTimeout ${t}ms`);
                res(777);
        
            }
            , t);
            console.log(`promise ${t}`);
        }
        ).then((result)=>{
            console.log(`result ${result}`)
        }
        );
        console.log("f-2")
    }

    如果customFun()的函数体内使用了await,也会执行customFun()的函数await行下面所有代码,然后再返回执行。

     结果为:
    customFun
    promise 1000
    setTimeout 1000ms
    result 777
    f-2

    1.实例

    async function f() {
        await console.log("f");
        console.log("f-2")
    }
    
    async function f0() {
        console.log("f0");
        await f();
        console.log("f0-2");
    }
    
    async function f1() {
        console.log("f1")
        await f0();
        //加了await, 会等到f0()的”f0-2"输出之后再输出f1-2;没加await,
        console.log("f1-2")
    
    }
    
    async function f2() {
        console.log("f2")
        await f1();
        console.log("f2-2")
    }
    
    // f2();
    // f2
    // f1
    // f0
    // f
    // f-2
    // f0-2
    // f1-2
    // f2-2

    2. 

    console.log("start")
    async function f() {
        console.log("f")
        await new Promise((res,rej)=>{
            let t = 1000;
            setTimeout(()=>{
                console.log(`setTimeout ${t}ms`);
                res(777);
        
            }
            , t);
            console.log(`promise ${t}`);
        }
        ).then((result)=>{
            console.log(`result ${result}`)
        }
        );
        console.log("f-2")
    }
    
    async function f0() {
        console.log("f0");
        await f();  //在这儿取消await 或者加上await,分析结果。
        console.log("f0-2");
    }
    
    async function f1() {
        console.log("f1")
        await f0();
        //加了await, 会等到f0()的”f0-2"输出之后再输出f1-2;没加await,
        console.log("f1-2")
    }
    async function f2() {
        console.log("f2")
        await f1();
        console.log("f2-2")
    }
    
    f2();
    console.log("end")
  • 相关阅读:
    Unix IPC之共享内存区(1)
    linux下的二进制文件的编辑和查看
    Posix 信号量
    Unix IPC之Posix信号量实现生产者消费者
    整型信号量与记录型信号量
    C++之友元
    C++之异常处理
    C++之STL(标准模板库)
    C++之继承
    C++之封装
  • 原文地址:https://www.cnblogs.com/sunupo/p/15566652.html
Copyright © 2011-2022 走看看