首页  >  文章  >  web前端  >  将 .then() 链接到 Promise 时如何避免未定义的值?

将 .then() 链接到 Promise 时如何避免未定义的值?

Linda Hamilton
Linda Hamilton原创
2024-10-19 22:18:29269浏览

How to Avoid Undefined Values When Chaining .then() to Promises?

将 .then() 链接到 Promise:避免未定义的值

将多个 .then() 方法链接到 Promise 时,重要的是从每个 .then() 处理程序返回一个值或 Promise,以避免在后续 .then() 调用中遇到未定义的值。

在您的示例中:

<code class="javascript">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>

这里的问题是首先 .then() 处理程序不返回任何值或 Promise。因此,当调用第二个 .then() 处理程序时,它没有任何可处理的内容。

要解决此问题,只需返回第一个 .then() 处理程序的结果即可:

<code class="javascript">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 the result to avoid undefined at next .then()
  });
}

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

现在,第二个 .then() 处理程序将接收第一个处理程序的结果作为数据参数,并且它不会是未定义的。

以上是将 .then() 链接到 Promise 时如何避免未定义的值?的详细内容。更多信息请关注PHP中文网其他相关文章!

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