首頁  >  文章  >  web前端  >  為什麼連結到 Promise 的 .then() 返回未定義?

為什麼連結到 Promise 的 .then() 返回未定義?

Susan Sarandon
Susan Sarandon原創
2024-10-19 22:17:29383瀏覽

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