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