首頁  >  文章  >  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