首頁 > web前端 > js教程 > 主體

將 .then() 連結到 Promise 時如何避免未定義的值?

Linda Hamilton
發布: 2024-10-19 22:18:29
原創
274 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!