Home > Web Front-end > JS Tutorial > body text

Why Does .then() Chained to a Promise Return Undefined?

Susan Sarandon
Release: 2024-10-19 22:17:29
Original
464 people have browsed it

Why Does .then() Chained to a Promise Return Undefined?

Why .then() Chained to a Promise Returns Undefined

Consider the code snippet below:

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

Why is the value of data undefined in the second .then() callback?

Answer:

When you chain a .then() callback to a Promise, it returns a new Promise that resolves to the return value of the callback. However, in the provided code, no value or Promise is returned from the first .then().

Solution:

To fix the issue, you need to return a value or invoke another function that returns a value or a Promise from the first .then(). Here's an updated version of the 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`);
    }

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

In this updated code, the first .then() returns the value of result (n multiplied by 10), which ensures that the second .then() receives a defined value as its argument.

The above is the detailed content of Why Does .then() Chained to a Promise Return Undefined?. 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