How do I return a value from a promise chain so the next step can use it?
Quick answer
Return the value you want the next .then() handler to receive. Returning an ordinary value passes it along; returning a promise makes the chain wait for that promise’s outcome. If a handler returns nothing, the next handler receives undefined. [S1] For asynchronous work inside a block-bodied handler, write return before the promise when later steps depend on its result.
The question, the details, the next step.
A practical checklist
For each
.then()handler, note the value it receives.Identify the exact value the next handler needs.
Return that value from the current handler.
If the next step depends on asynchronous work, return the promise for that work.
Check block-bodied handlers for a missing
returnand verify the called function's actual fulfillment value.
A few more useful answers
Why does an expression-bodied handler work without the word `return`?
An arrow function written as .then(value => transform(value)) implicitly returns its expression. If you add braces, write return explicitly: .then(value => { return transform(value); }).
What if I want the next step to receive the original value as well as a new result?
Return a combined value, such as an object: .then(original => calculate(original).then(result => ({ original, result }))). The next handler receives that object after the returned promise fulfills.
Does returning a promise guarantee the next step gets the value I expect?
No. The next handler receives the returned promise’s fulfillment value, but whether that is the value you expect depends on what the operation returns. [S1]
Sources
References used for this guide.
- [S1] Promise.prototype.then() — JavaScript | MDN developer.mozilla.org · Checked
