首页  >  文章  >  web前端  >  为什么链接到 Promise 的 .then() 返回未定义?

为什么链接到 Promise 的 .then() 返回未定义?

Susan Sarandon
Susan Sarandon原创
2024-10-19 22:17:29379浏览

Why Does .then() Chained to a Promise Return Undefined?

为什么链接到 Promise 的 .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`);
    }
  });
}

doStuff(9)
.then((data) => {
  console.log(data); // undefined, why?
});</code>

为什么第二个 .then() 回调中 data 的值未定义?

答案:

当你将 .then() 回调链接到 Promise 时,它返回一个新的 Promise,该 Promise 解析为回调的返回值。但是,在提供的代码中,第一个 .then() 没有返回任何值或 Promise。

解决方案:

要解决此问题,您需要返回一个值或调用另一个从第一个 .then() 返回值或 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`);
    }

    // Return `result` here to avoid undefined at chained `.then()`.
    return result;
  });
}

doStuff(9)
.then((data) => {
  console.log(`data is: ${data}`); // data is not undefined
});</code>

在此更新的代码中,第一个 .then() 返回 result 的值(n 乘以 10),这确保第二个 .then() 接收定义的值作为其参数。

以上是为什么链接到 Promise 的 .then() 返回未定义?的详细内容。更多信息请关注PHP中文网其他相关文章!

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