Home > Article > Web Front-end > 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>
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>
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!