Promise,async/await和Generator

五零二二

创建:2022-02-21 18:32      更新:2023-02-01 00:39

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)})

Generator生成器

function a(){
    setTimeout(()=>{
        let data = "data1";
        console.log(iterator.next(data));//next函数的参数,会作为上一个yield的返回值
    },1000);
    return "r1";
}
function b(){
    setTimeout(()=>{
        let data = "data2";
        console.log(iterator.next(data));
    },1000);
    return "r2";
}
function c(){
    setTimeout(()=>{
        let data = "data3";
        console.log(iterator.next(data));
    },1000);
    return "r3";
}
function* func(){
    let data1 = yield a();
    console.log(data1);
    let data2 = yield b();
    console.log(data2);
    let data3 = yield c();
    console.log(data3);
}
let iterator = func();
console.log(iterator.next());
//结果
//{"value": "r1","done": false}
//data1
//{"value": "r2","done": false}
//data2
//{"value": "r3","done": false}
//data3
//{"value": undefined,"done": true}

promise.all race allSettled的用法

all:将多个Promise包装后再返回 全部成功则返回一个结果数组,其顺序和传入的Promise数组顺序一致,但只要有错误则立即返回错误结果

race:返回最先得到结果的Promise,无论成功与否

allSettled:所有Promise执行结束后全部返回(包括错误结果),其顺序与传入的数组顺序一致,结果包含执行后的Promise状态

any:返回最先得到成功结果的Promise,全部错误则返回错误