promise-api

promise基础用法

 const a = 1,b=2;

    //promise基础用法
    const laopo = new Promise((resolve,reject)=>{
        if(a == 2){
            resolve(a);
        }else{
            reject(a-1);
        }
    })

    laopo.then(res=>{
        console.log('res',res);
    }).catch(err=>{
        console.log('err',err);
    })

    // 控制态打印:err 0

promise.all场景用法:在处理多个异步操作后再写回调逻辑

  const a1 = new Promise((resolve,reject)=>{
        if(a == 1){
            resolve(a);
        }else{
            reject(a-1);
        }
    })
    const a2 = new Promise((resolve,reject)=>{
        if(b == 2){
            resolve(b);
        }else{
            reject(b-1);
        }
    })
    Promise.all([a1,a2]).then(res=>{
        console.log('all-res',res);
    })
    // 控制态打印:all-res (2) [1, 2]

promise.race场景用法:Promise.race([p1, p2])里面哪个结果获得的快,就返回那个结果,不管结果本身是成功状态还是失败状态

let p1 = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('success')
        },1000)
    })

    let p2 = new Promise((resolve, reject) => {
        setTimeout(() => {
            reject('failed')
        }, 500)
    })

    Promise.race([p1, p2]).then((result) => {
        console.log('race-res',result)
    }).catch((error) => {
        console.log('race-error',error)
    })

    // 控制态打印:race-error failed

 

posted @ 2020-05-06 11:57  expworld  阅读(131)  评论(0编辑  收藏  举报