async与await以及宏微任务

async与await以及宏微任务

一个正在努力爱好运动的程序猿
座右铭:越努力越幸运,越运动越健康,热爱编程,热爱运动。



一、async与await

async function f(){  //async函数返回的是一个promise对象
        return 'f'
    }
    //f();  //Promise {<resolved>: "f"}
    f().then(function(res){   //默认为成功的状态,将该函数的返回值传给then的参数
        console.log(res)
    })

    async function f(){  //async函数返回的是一个promise对象
        return '1234'
    }
    f().then(res=>{
        console.log(res)
    });
    console.log(1);
    // 1     1234


    // await
    // await操作符用于等待一个Promise对象,它只能在异步函数async function内部使用。
    // 返回值:
    // 返回promise对象的处理结果,如果待等的不是promise对象,则返回该值本身
    // 如果一个promise被传递给一个await操作符,await将等待promise正常处理完成并返回其处理结果
    function f2(){
        console.log(4)
    }
    async function f(){
        await f2();     
        console.log(2)   
    }
    f();
    console.log(3); 

    //正常情况下,await命令后面是一个promise对象,它也可以是其它值,如字符串,布尔值,数值以及普通函数。
    console.log(2)
    async function fn(){
        console.log(3)
        await 100;  
        console.log(1)
    }
    fn()
    console.log(4)

    //await命令后面是一个promise对象
    function p(){
        return new Promise(resolve=>{
            resolve();
            console.log(1)
        });
    };
    async function fn(){
        console.log(2)
        await p();  
        console.log(3)
    }
    fn()

二、宏微任务

    //宏任务  setTimeout   setInterval 
    //微任务  promise中的then  async await

    //promise是同步还是异步?
    console.log(1);  //同步
    let a = new Promise((res,rej)=>{
        console.log(2)  //同步
    });
    console.log(3); //同步
    let a2 = new Promise((res,rej)=>{
        console.log(4)  //同步
    });
    console.log(5);   //同步
 

    console.log(1)   //同步
    let a = new Promise((res,rej) => {  
        res();
        console.log(2); //同步
    });
    a.then(() => {    //异步
        console.log(3)
    })
    console.log(4);  //同步
    let b = new Promise((res,rej) => {  
        res();
        console.log(5);  //同步
    });
    b.then(() => {  
        console.log(6) //异步
    })
    console.log(7);   //同步


    setTimeout(()=>{  //宏任务
        console.log(1)
    },0)
   new Promise((res,rej) => {  
        res();
        console.log(2);  //同步
    }).then(() => {  
        console.log(3) //微任务
    })
    console.log(4)  //同步


    async function f(){  //async函数返回的是一个promise对象
        console.log(5)  //同步
        return '1234'
    }
    f().then(res=>{   //微任务
        console.log(res)
    });
    console.log(1);   //同步
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值