Home > Web Front-end > JS Tutorial > How to Avoid Undefined Values When Chaining .then() to Promises?

How to Avoid Undefined Values When Chaining .then() to Promises?

Linda Hamilton
Release: 2024-10-19 22:18:29
Original
378 people have browsed it

How to Avoid Undefined Values When Chaining .then() to Promises?

Chaining .then() to Promises: Avoiding Undefined Values

When chaining multiple .then() methods to a Promise, it's important to return a value or Promise from each .then() handler to avoid encountering undefined values at subsequent .then() calls.

In your example:

<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>
Copy after login

The issue here is that the first .then() handler does not return any value or Promise. As a result, when the second .then() handler is called, it doesn't have anything to work with.

To fix this, simply return the result from the first .then() handler:

<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>
Copy after login

Now, the second .then() handler will receive the result from the first handler as the data parameter, and it will not be undefined.

The above is the detailed content of How to Avoid Undefined Values When Chaining .then() to Promises?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template