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>
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>
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!