错误和承诺
Promise 以不同于同步或回调驱动代码的方式处理错误。
const p = new Promise(function (resolve, reject) {
reject(new Error('Oops'));
});
// anything that is `reject`ed inside a promise will be available through catch
// while a promise is rejected, `.then` will not be called
p
.then(() => {
console.log("won't be called");
})
.catch(e => {
console.log(e.message); // output: Oops
})
// once the error is caught, execution flow resumes
.then(() => {
console.log('hello!'); // output: hello!
});
目前,未捕获的承诺中抛出的错误会导致吞下错误,这可能导致难以追踪错误。这可以使用像 eslint 这样的 linting 工具来解决, 或者确保你总是有一个 catch
子句。