在承诺中捕获拒绝的问题

Problem with catching the reject in promises

我有一个练习来做出以失败结尾的承诺,returns 字符串“Failure”。我必须使用 then 来操纵错误。

问题是我的输出只是 reject 的原因,它甚至没有转到 then 也没有 console.log 我的字符串

我的代码:

const myPromise = new Promise((resolve, reject) => {
    reject("failure").then(console.log("ended with failure"))
})
console.log(myPromise)

我做错了什么?

正确的做法是。

const myPromise = new Promise((resolve, reject) => {
      reject("failure");
})
myPromise.catch(() => console.log("Caught an error!"));

resolvereject 只是改变承诺状态的函数,而不是承诺本身。

UPD:请查看此文档https://javascript.info/promise-basics它可能有助于学习承诺。

使用 .then() & .catch() 方法处理承诺。

这些方法恰好在 promise 为:

时被调用
  • 已解决,
  • 拒绝

记住这一点:

  • 只要承诺在没有任何错误或拒绝的情况下得到解决,它就会进入 .then 方法。
  • 如果有错误、异常或拒绝,它会进入.catch 方法。

让我们看一个成功解决承诺的例子。

const myPromise = new Promise((resolve, reject) => {
  resolve("this will resolve this promise");
});

myPromise
  .then((elem) => console.log("Promise resolved came in .then block"))
  .catch((error) => console.log("promise with error came in .catch block ", error));

// prints 
// this will resolve this promise
// Promise resolved came in .then block

示例 # 2: 拒绝示例:

// a rejected promise goes to .catch block
const myPromise = new Promise((resolve, reject) => {
  reject("this will reject this promise");
});

myPromise
  .then((elem) => console.log("Promise resolved came in .then block"))
  .catch((error) => console.log("promise with error came in .catch block ", error));

// prints 
// this will reject this promise
// promise with error came in .catch block 

示例 # 3: 错误示例:

// incase of error goes to .catch block
const myPromise = new Promise((resolve, reject) => {
  throw "sample exception";
});

myPromise
  .then((elem) => console.log("Promise resolved came in .then block"))
  .catch((error) => console.log("promise with error came in .catch block ", error));

// prints 
// promise with error came in .catch block 

希望您现在了解这些块的用途。如果有任何问题,请告诉我。