종우의 컴퓨터 공간

Difference between promises and async/await in Node.js 본문

Preparing Interviews/JavaScript Fundamentals

Difference between promises and async/await in Node.js

종우공간 2021. 10. 4. 14:49

What Is Promises?


A promise in NodeJS is similar to a promise in real life. It is an assurance that something will be done. Promises is used to keep track of whether the asynchronous event has been executed or not and determines what happens after the event has occurred. It is an object having 3 states. 

What Are Three States In Promises?


· Pending: Initial State, before the event has happened

· Resolved: After the operation completed successfully

· Rejected: If the operation had error during execution, the promise fails

What is Async/Await?


Async/await is used to work with promises in asynchronous functions. It is basically syntactic sugar(In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express) for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.

Await can be only used in async functions. It is used for calling an async function and waits for it to resolve or reject. Await blocks the execution of the code within the async function in which it is located.

Error Handling In Async/Await


For a successful resolved promise, we use try and for rejected promise, we use catch. To run a code after the promise has been handled using try or catch, we can .finally() method. The code inside .finally() method runs once regardless of the state of the promise.

Differences Between Promise And Async/Await


  Promise Async/Await
1. Promise is an object representing intermediate state of an operation which is guaranteed to complete its execution at some point in future Async/Await is a syntactic sugar for promises, a wrapper making the code execute more synchronously
2. Promise has three states - pending, resolved, and rejected It does not have any states. It returns a promise either resolved or rejected
3. Error handling is done using .then() and .catch() method Error handling is done using .try() and .catch() method
4. Promise chains can become difficult to understand sometimes Using async/await makes it easier to read and understand the flow of the program as compared to promise chains

Reference


https://www.geeksforgeeks.org/difference-between-promise-and-async-await-in-node-js/

 

Difference between promise and async await in Node.js - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

'Preparing Interviews > JavaScript Fundamentals' 카테고리의 다른 글

Functions (Higher-order, Callback)  (0) 2021.09.23