Promise.all 使用方法

1.await 可以获得多个promise 的返回结果

2. Promise.all 返回的也是promise,所以可以直接await Promise.all();

1. 使用Promise

function fn(){
    return new Promise((resolve,reject)=>{
        let randomNum = parseInt(Math.random()*6+1);
        console.log(randomNum);
        if(randomNum>3){
            resolve('买'); 
        }
        else{
            reject('不买');
        }
    })
}

Promise.all([fn(),fn()]).then((x)=>{console.log(x,'success')},(y)=>{console.log(y,'error');});
  • Promise.all 里面参数为一个数组,数组的每一项是一个返回promise 的函数调用
  • then 的第一个参数是所有promise都成功的调用,返回结果是一个数组,数组的每一项为函数promise 的返回结果。
  • then 的第二个参数:返回结果有一个失败则执行失败的回调,拿到的是第一个失败的值

2. 使用await

await 是可以获得多个promise 返回结果的,Promise.all()返回的也是promise结果。所以想要使用await 拿到多个promise的返回值,可以直接await Promise.all();

function fn(){
    return new Promise((resolve,reject)=>{
        let randomNum = parseInt(Math.random()*6+1);
        console.log(randomNum);
        if(randomNum>3){
            resolve('买'); 
        }
        else{
            reject('不买');
        }
    })
}
async function test(){
    try{
    let res = await Promise.all([fn(),fn()]);
    console.log(res,'success');
    }
    catch(error){
        console.log(error,'error');
    }
}

test();
  • Promise.all([fn(),fn()]) 都返回resolve(); 才能够拿到成功的返回值
  • Promise.all([fn(),fn()]) 有一个返回reject(), 则进入catch(error), 拿到失败的返回值
  • 6
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值