promise、async和await

2 篇文章 0 订阅

async:
async function 声明将定义一个返回 AsyncFunction 对象的异步函数。
当调用一个 async 函数时,会返回一个 Promise 对象。当这个 async 函数返回一个值时,Promise 的 resolve 方法会负责传递这个值;当 async 函数抛出异常时,Promise 的 reject 方法也会传递这个异常值。
(async函数返回一个 Promise 对象,当函数执行的时候,一旦遇到 await 就会先返回,等到触发的异步操作完成,再接着执行函数体内后面的语句。)

await:
语法:[return_value] = await expression;
表达式(express):一个 Promise 对象或者任何要等待的值。返回值(return_value):返回 Promise 对象的处理结果。如果等待的不是 Promise 对象,则返回该值本身。
(await必须和async一起使用)

// demo1的setTimeout完成后执行demo2
function demo1(){
    return new Promise(function(resolve, reject){
        //异步操作
        setTimeout(function(){
            resolve({
                type:'success',
                data:'demo1的async异步完成'
            });       
        }, 1000);
    });          
}

function demo2(){
    console.log('我是demo2')
}


async function getP(){
    const p = await demo1(); // {type:'success',data:'demo1的async异步完成'}
    return p; 
}

//getP()是一个Promise 对象
getP().then((res)=>{
    console.log(res.data); // demo1的async异步完成
    demo2();
})

// 运行的结果:
// demo1的async异步完成
// 我是demo2

Promise:

Promise是一个构造函数,身上有all、reject、resolve这几个方法,原型上有then、catch方法.

all:并行执行异步操作,并且在所有异步操作执行完后才执行回调;

resolve:异步操作执行成功后的回调函数

reject:异步操作执行失败后的回调函数,把Promise的状态置为rejected,我们在then中能捕捉到,然后执行“失败”情况的回调;

then:用于多层回调,(可传两个函数,第一个是成功的回调,第二个是失败的回调函数

catch:在执行resolve的回调(也就是hen中的第一个参数)时,如果抛出异常了(代码出错了),那么并不会报错卡死js,而是会进到这个catch方法中

用法:

调用方式二:
resolveMethods1()
.then(function (data) {
    console.log(data);
    return resolveMethods1();
})
.catch(function (data) {
    console.log(data);
    return resolveMethods2();
})
.then(function (data) {
    console.log(data);
})
.catch(function (data) {
    console.log(data);
});
结果如下(方式一和方式二的结果是一样的):

promise,settimeout,dom等执行顺序:

console.log(1) // 第一执行
setTimeout(() => {console.log(2);alert(2)},0) // 第五执行
Promise.resolve().then(() => {console.log(3);alert(3)}) // 第三执行
document.querySelector('body').innerHTML = 'ddddd' // 第四执行
console.log(4)// 第二执行

结果  1,4,3,undefined(插入dom),2 

 总结: 同步任务 > 微任务 > DOM渲染 > 宏任务

什么是宏任务?
settimeout,  setInterval, DOM事件, ajax请求

什么是微任务?
promise, async/await

 promise实现原理:

实现思路步骤: 

1.先定义一个MyPromise,里面定义属性 状态(pending,fullfilled,rejected), 成功的结果,失败的结果.定义函数resolve,reject,这俩是给(new MyPromise)里面调用的
2.初始化回调函数cb(resolve,reject),做try,catch处理报错就走reject, 
3.定义resolve和reject函数,只有当状态未pending的的状态下才能运行resolve和reject函数
4.定义then方法,MyPromise.prototype.then,传入onFull参数,即then的回调函数,
5.判断当前状态是否为fullfilled,代表new MyPromise()里面resolve已经调用了,
  如果状态为pending则表示new MyPromise()里面有异步,将当前then的参数存储到数组callbackResolveFnList里面起来,
  然后异步执行完成后会调用resolve,此时在resolve里面将callbackResolveFnList里面的函数依次执行并传参(成功的结果).
6.链式调用,如果想要得到().then().then().then().then().then()的话,那么在MyPromise.prototype.then里面就需要返回一个new MyPromise(...)
7.取MyPromise.prototype.then的参数(一个函数)执行结果,即调用.then().then()的时候里面的返回值,这个返回值可能是一个新的new MyPromise,也可能不是,
  1.().then(ret => '我是返回值');
  2.().then(ret => {
    return new MyPromise((resolve, reject) => {...}) 
  })
  MyPromise.prototype.then里面判断 返回值的类型 如果是MyPromise则代表是第二种,所以需要执行将他的ret.then(resolve, reject)方法,否则执行resolve(ret)
  
 上面是 fullfilled的处理,如果是pending的话,同样返回new MyPromise(...),需要将存入数组的方法用一个function 包裹起来,fn里面做判断,思路同fullfilled,

代码就不贴了,拜拜!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值