Differences between promises and async/await
Note: The list below can be matched with the numbers described below.
- A promise represents a process that guaranteed to complete the execution.
- Promises have 3 states, these states are pending, resolved, and rejected.
- If the promise is chained with .then(), that continues the execution after adding the function to the callback chain.
- Error handling can be done with .then() and .catch() methods.
- Promise chaining can be difficult to understand and follow.
- Debugging can be very tricky with multiple promise chaining.
- Promises can be used for multiple promises in the promise chaining.
- Async await is syntactic sugar for promises. Making code looks like executed synchronously.
- Async await does not have states. Async functions return a promise. This promise state can be either resolved or rejected.
- Await suspends the called function execution until the promise returns a result for that execution. If there are other functions been called after await, these executions wait until the promise finishes.
- Error handling can be done with a try-catch block.
- Async/Await makes reading the promises flow much easier. Understanding the functionality is also very easy compared to promises.
- Debugging is much easier with async/await.
- Await can be used for a single promise or promise.all().
Should you use promises or async/await?
- If you are using another asynchronous function which is depending on the first asynchronous function, you should use await to wait first one to finish instead of promise chaining.
- Await keyword blocks the execution for the next lines until it finishes. If you don’t need to block the execution you can call the async function without await. (For example, push notifications, if you don’t want to check the status of a push notification has been delivered or not you can skip await keyword, and code execution will continue asynchronously)
- If there are multiple asynchronous functions that can be run in parallel, you can use promise.all([promise1,promise2]) to run them in parallel.
- Using async/await definitely will help you to understand asynchronous processes much faster.
- Instead of using promise chaining async / await provides a much cleaner code.
- If you are using many microservices and asynchronous functions using async / await will help you to debug your code much faster. Generating the breakpoints in the promise chaining can be really tricky.
- Async await makes asynchronous code look like synchronous code.
- To catch errors in the promises always requires you to write the .catch() block.
- Async await can be written in the try-catch block along with all other codes.
Follow me on Twitter
Subscribe for more on Youtube