Skip to content

Commit a24dbaf

Browse files
committed
Promises and async-await
1 parent 138e09b commit a24dbaf

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

README.md

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3004,7 +3004,56 @@ moreWork(); // will run before console.log
30043004
<b><a href="#">↥ back to top</a></b>
30053005
</div>
30063006

3007-
#### Q. ***What is difference between promise and async await in Node.js?***
3007+
## Q. ***What is difference between promises and async-await in Node.js?***
3008+
3009+
**1. Promises**
3010+
3011+
A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed. This way, other operations can keep running without interruption.
3012+
3013+
**States of Promises:**
3014+
3015+
* `Pending`: Initial State, before the Promise succeeds or fails.
3016+
* `Resolved`: Completed Promise
3017+
* `Rejected`: Failed Promise, throw an error
3018+
3019+
*Example:*
3020+
3021+
```js
3022+
function logFetch(url) {
3023+
return fetch(url)
3024+
.then(response => {
3025+
console.log(response);
3026+
})
3027+
.catch(err => {
3028+
console.error('fetch failed', err);
3029+
});
3030+
}
3031+
```
3032+
3033+
**2. Async-Await**
3034+
3035+
`Await` is basically syntactic sugar for **Promises**. It makes asynchronous code look more like synchronous/procedural code, which is easier for humans to understand.
3036+
3037+
Putting the keyword `async` before a function tells the function to return a Promise. If the code returns something that is not a `Promise`, then JavaScript automatically wraps it into a resolved promise with that value. The `await` keyword simply makes JavaScript wait until that `Promise` settles and then returns its result.
3038+
3039+
*Example:*
3040+
3041+
```js
3042+
async function logFetch(url) {
3043+
try {
3044+
const response = await fetch(url);
3045+
console.log(response);
3046+
}
3047+
catch (err) {
3048+
console.log('fetch failed', err);
3049+
}
3050+
}
3051+
```
3052+
3053+
<div align="right">
3054+
<b><a href="#">↥ back to top</a></b>
3055+
</div>
3056+
30083057
#### Q. ***How to use JSON Web Token (JWT) for authentication in Node.js?***
30093058
#### Q. ***How to build a microservices architecture with Node.js?***
30103059
#### Q. ***How to use Q promise in Node.js?***

0 commit comments

Comments
 (0)