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")
  • 相关阅读:
    AIX6.1 线程模型说明
    多线程专题之线程死锁原因之谜
    多线程执行顺序诡异现象谈,你不知道的pthread_create
    SOA体系结构基础培训教程-规范标准篇
    C# AES要解密的数据的长度无效
    winform命名规范
    winform 打开一个窗体,关闭一个窗体
    VS2017专业版和企业版激活密钥
    AES五种加密模式
    c#POST请求php接口
  • 原文地址:https://www.cnblogs.com/sunupo/p/15566652.html
Copyright © 2011-2022 走看看