View profile

Do You Need Promise Chaining With Async/Await?

Promise chaining is a pattern for composing async logic using promises. You can chain promises togeth
Do You Need Promise Chaining With Async/Await?
By Mastering JS Weekly • Issue #29 • View online
Promise chaining is a pattern for composing async logic using promises. You can chain promises together by putting a function that returns a promise as the `onFulfilled()` parameter to the `then()` function.

Chaining 3 promises together, one `then()` after the other.
Chaining 3 promises together, one `then()` after the other.
Promise chains are great for sequential operations with minimal branching. But they get unwieldy as soon as you start needing multiple async operations within an `if` statement or any other sort of significant branching. That’s where async/await comes in.
Async/await’s killer feature is that you can build async logic using CS101 concepts: for loops, if statements, try/catch. There’s nothing you can do with async/await that you can’t do with a sufficiently convoluted promise chain, but async/await makes your code much more readable.
Async/await: so easy, a first week coding bootcamp student can grok it.
Async/await: so easy, a first week coding bootcamp student can grok it.
However, you can mix promise chaining with async/await to get some neat design patterns. For example, Axios requests return complex nested response objects. What if you just want to get the JSON response body? You can combine `await` with a minimal promise chain.
Async/await with a promise chain to format the async response.
Async/await with a promise chain to format the async response.
There are also things you can do that you shouldn’t. A surefire way to look like an amateur is to put an async function as an `onFulfilled()` callback to `.then()`:
Use promise chaining within async functions, not the other way around.
Use promise chaining within async functions, not the other way around.
When you mix async functions and promise chains, make sure you use promise chains within an async function underneath an `await`. Don’t use an async function as an `onFulfilled()` callback, or, worse yet, use an async function as a promise executor. Promise chains can provide some convenience within async functions, but there’s no sense in nesting async functions in promise chains.
Most Recent Tutorials
Other Interesting Reads
Working With AWS Route 53 in Node.js | www.thecodebarbarian.com
Did you enjoy this issue?
Mastering JS Weekly

A weekly summary of our tutorials

If you don't want these updates anymore, please unsubscribe here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue