首页  >  文章  >  web前端  >  为什么承诺链在某些情况下返回未定义?

为什么承诺链在某些情况下返回未定义?

Susan Sarandon
Susan Sarandon原创
2024-10-19 22:15:02343浏览

Why Does Promise Chaining Return Undefined in Some Cases?

为什么 Promise 链中 .then() 返回的是 undefined?

Promise 链中,.then() 返回一个新的 Promise 对象。但是,如果 .then() 回调未显式返回任何值或 Promise,则生成的 Promise 将解析为未定义。

请考虑以下代码:

<code class="js">function doStuff(n) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(n * 10);
    }, Math.floor(Math.random() * 1000));
  })
  .then(result => {
    if (result > 100) {
      console.log(result + " is greater than 100");
    } else {
      console.log(result + " is not greater than 100");
    }
  });
}

doStuff(9)
.then(data => {
  console.log(data); // Undefined
});</code>

在此代码中, data 在最后一个 .then() 中未定义,因为第一个 .then() 不返回任何值。为了解决这个问题,我们可以修改第一个 .then() 以返回结果值:

<code class="js">function doStuff(n) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(n * 10);
    }, Math.floor(Math.random() * 1000));
  })
  .then(result => {
    if (result > 100) {
      console.log(result + " is greater than 100");
    } else {
      console.log(result + " is not greater than 100");
    }
    return result; // Return result to avoid undefined
  });
}

doStuff(9)
.then(data => {
  console.log("data is: " + data); // data is no longer undefined
});</code>

以上是为什么承诺链在某些情况下返回未定义?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn