Home  >  Article  >  Web Front-end  >  Why Does Promise Chaining Return Undefined in Some Cases?

Why Does Promise Chaining Return Undefined in Some Cases?

Susan Sarandon
Susan SarandonOriginal
2024-10-19 22:15:02343browse

Why Does Promise Chaining Return Undefined in Some Cases?

Why is undefined returned by .then() in Promise Chaining?

In Promise chaining, .then() returns a new Promise object. However, if no value or Promise is explicitly returned from the .then() callback, the resulting Promise will resolve to undefined.

Consider the following code:

<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
});</code>

In this code, data is undefined in the final .then() because the first .then() does not return any value. To fix this, we can modify the first .then() to return the result value:

<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; // Return result to avoid undefined
  });
}

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

The above is the detailed content of Why Does Promise Chaining Return Undefined in Some Cases?. 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