javascript 我遇到了UnhandledPromiseRejection的问题,不知道如何解决

rbl8hiat  于 2023-02-21  发布在  Java
关注(0)|答案(2)|浏览(389)

我正在用这段代码学习一节课程,然后出现了以下错误:

This error originated either by throwing inside of an async function without a 
catch block, or by rejecting a promise which was not handled with .catch(). 
The promise rejected with the reason "That item is sold out.".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

这是密码:

const inventory = {
  sunglasses: 0,
  pants: 1088,
  bags: 1344
};

// Write your code below:
const myExecutor = (resolve, reject) =>{
  if(inventory.sunglasses > 0){
    resolve('Sunglasses order processed.');
  }else{
    reject('That item is sold out.');
  }
}

const orderSunglasses = () => {
  return new Promise(myExecutor);
}

const orderPromise = orderSunglasses();
console.log(orderPromise);

我试着在网上找到错误和阅读别人的错误,但不清楚,但我不知道,我是新的javascript。

dced5bon

dced5bon1#

const myExecutor = new Promise((resolve, reject) =>{
  if(inventory.sunglasses > 0){
    resolve('Sunglasses order processed.');
  }else{
    reject('That item is sold out.');
  }
});

const orderSunglasses = () => {
  return myExecutor;
}

const orderPromise = orderSunglasses();
orderPromise.then((value)=>console.log(value)).catch((err)=>console.log(err));

使用then和catch方法检查您的承诺是否已被解析或拒绝,因为它处理两种类型的值。如果您不检查catch块中的错误,它将抛出一个错误,表示拒绝未使用.catch()处理的承诺

gkl3eglg

gkl3eglg2#

在典型的承诺消费中,我们不知道承诺是被解析还是被拒绝,所以我们需要为这两种情况提供逻辑,我们可以将成功回调和失败回调都传递给.then()。

const inventory = {
  sunglasses: 0,
  pants: 1088,
  bags: 1344
};

// Write your code below:
let prom = new Promise((resolve, reject) =>{
  if(inventory.sunglasses > 0){
    resolve('Sunglasses order processed.');
  }else{
    reject('That item is sold out.');
  }
});

const handleSuccess = (resolvedValue) => {
  console.log(resolvedValue);
};
 
const handleFailure = (rejectionReason) => {
  console.log(rejectionReason);
};
 
prom.then(handleSuccess, handleFailure);

相关问题