Home > Web Front-end > JS Tutorial > Why Do Promises Chain Without Returning a Value Result in Undefined Values?

Why Do Promises Chain Without Returning a Value Result in Undefined Values?

Mary-Kate Olsen
Release: 2024-10-19 22:13:29
Original
703 people have browsed it

Why Do Promises Chain Without Returning a Value Result in Undefined Values?

Understanding the Undefined Value in Chained Promises

In JavaScript, Promises are used for asynchronous operations. They provide a way to handle the results of computations and handle scenarios such as success and failure. However, sometimes we encounter an unexpected value of undefined when chaining Promises.

Root Cause: Chaining Without Returning Value

Promises are chained using the .then() method. When a Promise is resolved or rejected, the .then() method returns a new Promise object. However, if no value or Promise is explicitly returned from the .then() method, the new Promise object will become resolved with a default value of undefined.

Example:

<code class="javascript">doStuff(9)
  .then(function(result) {
    // No value or Promise returned
    if (result > 100) {
      console.log(result + " is greater than 100");
    } else {
      console.log(result + " is not greater than 100");
    }
  })
  .then(function(data) {
    console.log(data); // Output: undefined
  });</code>
Copy after login

In this example, the first .then() method does not return any value. As a result, the second .then() method receives undefined as its argument, which is then printed to the console.

Solution: Returning a Value or Promise

To avoid undefined values in chained Promises, a value or a promise that returns a value must be explicitly returned from the .then() method.

Example:

<code class="javascript">doStuff(9)
  .then(function(result) {
    if (result > 100) {
      console.log(result + " is greater than 100");
    } else {
      console.log(result + " is not greater than 100");
    }
    // Return the result to avoid undefined at the next .then()
    return result;
  })
  .then(function(data) {
    console.log("data is: " + data); // Output: "data is: 90"
  });</code>
Copy after login

By returning the result, the second .then() method receives the actual result value instead of undefined.

The above is the detailed content of Why Do Promises Chain Without Returning a Value Result in Undefined Values?. 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