从循环中捕获承诺错误

时间:2017-04-26 21:15:06

标签: javascript node.js promise

我需要在for循环中调用多个promise,但在每次运行期间它都会给我unhandled promise exception。解决这个问题的方法是返回第二个promise,这样就可以执行最后一个catch并且它可以正常工作,但是 - 不会执行第二次和更多迭代。

const doFirstThing = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (resolve(['a', 'b', 'c'])), 1000);
    });
}

const doSecondThing = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (reject('test')), 500); // reject here
    });
}

doFirstThing()
.then(results => {
    results.forEach(result => {
        doSecondThing(result)
        .then(() => console.log(result, 'done'));
    });
})
.catch(error => console.log(error));

我该如何处理?

1 个答案:

答案 0 :(得分:1)

阻止unhandled promise exception.catch().then();使用Promise.all().map()代替.forEach()

const doFirstThing = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (resolve(['a', 'b', 'c'])), 1000);
    })
}

const doSecondThing = (r) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (reject('test')), 500); // reject here
    })
}

doFirstThing()
.then(results => {
    return Promise.all(results.map(result => {
        return doSecondThing(result)
    }));
})
.then((result) => console.log(result, 'done'))
.catch(error => console.log(`err:${error}`));