Promise,async/await

五零二二

创建:2022-02-21 18:32      更新:2022-08-22 23:36

async将返回一个Promise对象,await只能用在async内部,如果其等待的是一个Promise对象,它会阻塞async内部之后的代码运行,等待其后接的Promise运行结束,并将其得到的resolve作为自己的运算结果

async function async1(){
    console.log('async1 start');
    let str = await async2();//await会阻塞后面的代码运行,等待async2中的setTimeout运行结束,并将resolve作为自己的运算结果返回
    console.log(str);//输出async2-2 timeout
    console.log('async1 end')
}
function async2(){
    console.log('async2');
    return new Promise(resolve => {
        setTimeout(() => resolve("async2-2 timeout"), 1000);
    });
}
console.log('script start');
async1();
console.log('script end');

//将async/await改写为普通Promise模式
function async2(){
    console.log('async2');
    return new Promise(resolve => {
        setTimeout(() => resolve("async2-2 timeout"), 1000);
    });
}
console.log('script start');
let asp1 = new Promise(res =>{
    console.log('async1 start');
    async2().then((str)=>{
        console.log(str);
        console.log('async1 end');
    });
})
console.log('script end');

await无法接收rejected,需要用try...catch去处理

async function async1(){
    try{
        let str = await async2();
        console.log(str);
    }catch(err){console.log(err)}
}
function async2(){
    return new Promise((resolve,rejected) => {
        setTimeout(() => rejected("async2-2 timeout"), 1000);
    });
}
async1();
const promise = new Promise((resolve,reject)=>{
    console.log(1);
    resolve();
    console.log(2);
})

//.then()异步操作
promise.then(()=>{
    console.log(3);
})
console.log(4);
// 1243

模拟一个Promise

function ceShi(fn){
    this.status = "pending";//当前执行状态
    this.success = null;//成功数据缓存
    this.error = null;//失败数据缓存

    //实现异步 将then和catch的回调方法进行缓存
    this.onFulfilledCallbacks = [];
    this.onRejectedCallbacks = [];
    a = (text)=>{
        if(this.status === "pending"){
            this.status = "fulfilled";
            this.success = text;
            //异步执行完毕后将缓存的回调函数依次执行
            this.onFulfilledCallbacks.forEach(item=>item(text))
        }
    }
    b = (text)=>{
        if(this.status === "pending"){
            this.status = "rejected";
            this.error = text;
            this.onRejectedCallbacks.forEach(item=>item(text))
        }
    }
    try{
        fn(a,b)
    }catch(err){
        b(err)
    }
}
ceShi.prototype.then = function(fn){
    if(this.status==="pending"){
        //将回调函数缓存
        this.onFulfilledCallbacks.push(fn)
    }
    return this;
}
ceShi.prototype.catch = function(fn){
    if(this.status==="pending"){
        this.onRejectedCallbacks.push(fn)
    }
    return this;
}
function ccc(status){
    return new ceShi((a,b)=>{
        if(status){
            setTimeout(()=>{a("success!")},2000)
        }else{b("error!")}
    })
}
ccc(1).then((res)=>{console.log(res)}).catch((err)=>{console.log(err)})

promise.all race allSettled的用法

all:将多个Promise包装后再返回 全部正确则返回一个结果数组,和传入的Promise数组顺序一致 只要有错误则立即返回错误结果 race:返回最先得到结果的Promise allSettled:所有Promise执行结束后全部返回(包括错误结果),顺序与传入的数组一致,结果包含执行后的Promise状态