promise、async、await

promise是es6的新语法,用来解决回调地狱的。

口述promise构造函数会接受一个函数作为参数,该函数中有resolve和reject两个参数分别对应着then和catch两个方法;当调用resolve的时候就会执行then方法,调用reject时救护执行catch方法。

语法:
   new Promise(function(resolve, rejct){
        成功就调用resolve
        失败就调用reject
    }).then(res => {

    }).catch(res => {

    })

同步和异步:new promise中的回调函数是同步代码,promise对象的then方法是异步代码

   new Promise(
        function (resolve) {
            console.log(1);
            resolve(2)
        }
        // 这个匿名函数中的代码是同步的
    ).then(res => { // then才是异步的
        console.log(res);
    })

    console.log(3);

// 结果是  1 3 2  ,所以new Promise中的回调函数是同步代码,promise对象的then方法才是异步代码

回调地狱的终极解决方案 async:

async function fn(a, b) {
        return a + b
        // 调用async会先return new Promise(function(resolve){
        // resolve(a + b)
        // })
    }

    var res = fn(1, 2) 
    console.log(res); // 输出promise对象
    res.then(res => { // 要得到原先函数中返回的结果,需要调用then方法得到
        console.log(res); //输出3
    })

作用:简化promise的使用(不用再使用then()来指定成功或失败的回调函数)以同步编码的方式实现异步流程(没有回调函数)。

asyncasync函数在调用后,会得到一个promise对象,如果要得到其中返回的值,需要调用promise对象的then方法;当函数执行的时候,一旦遇到 await 就会先返回,等到触发的异步操作完成,再接着执行函数体内后面的语句。

注意点:1.await 命令只能用在 async 函数之中,如果用在普通函数,就会报错。

               2.如果async修饰的函数中没有await关键字, 跟普通函数一样,就是同步函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值