• 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")
  • 相关阅读:
    js日期加减得到新的日期的自定义函数
    c# winform 一个可以用鼠标改变控件位置和大小的类,调用即可
    颜色英文代码全集
    你的Web系统有多少安全漏洞
    robots协议和禁止搜索引擎收录
    Linux下./configure错误详解
    c# winform 关于DataGridView的一些操作
    通过JSONP实现完美跨域
    tabs选项卡
    jQuery 1.4的十五大新功能实例精讲
  • 原文地址:https://www.cnblogs.com/sunupo/p/15566652.html
Copyright © 2020-2023  润新知