与承诺的互动

Version >= 6

例外情况是同步代码拒绝基于承诺的异步代码。如果在 promise 处理程序中抛出异常,则会自动捕获其错误并用于拒绝 promise。

Promise.resolve(5)
    .then(result => {
        throw new Error("I don't like five");
    })
    .then(result => {
        console.info("Promise resolved: " + result);
    })
    .catch(error => {
        console.error("Promise rejected: " + error);
    });
Promise rejected: Error: I don't like five

Version > 7

异步函数提案在相反方向 -expected 是 ECMAScript 的一部分 2017-延伸此。如果你等待被拒绝的承诺,则会将其错误引发为异常:

async function main() {
  try {
    await Promise.reject(new Error("Invalid something"));
  } catch (error) {
    console.log("Caught error: " + error);
  }
}
main();
Caught error: Invalid something