Promise.all find which promise rejected

前端 未结 2 771
眼角桃花
眼角桃花 2021-02-05 16:31

In my code, I am using Promise.all() to run code asynchronously once some promises have all fulfilled. Sometimes, one promise will fail, and I\'m not sure why.

2条回答
  •  甜味超标
    2021-02-05 16:58

    You can use an onreject handler on each promise:

    Promise.all(promises.map((promise, i) =>
        promise.catch(err => {
            err.index = i;
            throw err;
        });
    )).then(results => {
        console.log("everything worked fine, I got ", results);
    }, err => {
        console.error("promise No "+err.index+" failed with ", err);
    });
    

    In general, every rejection reason should contain enough information to identify the issue that you need to handle (or log).

提交回复
热议问题