Home >Web Front-end >JS Tutorial >What Causes Undefined Values in Chained Promises and How to Fix Them?

What Causes Undefined Values in Chained Promises and How to Fix Them?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-19 22:19:02739browse

What Causes Undefined Values in Chained Promises and How to Fix Them?

Chained Promises and the Value of Undefined

In this case, the chained .then() does not return any value or create a new Promise. When the outer promise created in doStuff() resolves with the value of n * 10, the subsequent .then() is invoked, and the result of the expression within it (logging statements and a potential return statement) is logged to the console. However, since no actual value is returned from this chained .then(), the subsequent .then() chained to it in doStuff receives nothing—hence the undefined value.

Solution: Returning Values or Promises from .then()

To resolve this issue, ensure that the .then() callback returns a value or another function call that returns a value or a Promise. In this modified example:

<code class="js">const doStuff = (n /* `n` is expected to be a positive number */) => {
  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` to pass it to the next `.then()`
      return result;
    });
};

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

Now, the chained .then() receives the value returned from the previous .then(), eliminating the undefined issue. The output will display the value passed on from the previous .then().

The above is the detailed content of What Causes Undefined Values in Chained Promises and How to Fix Them?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn