Wednesday, 10 May 2023

Three ways to use asynchronous in nodejs

* There are 3 ways to use asynchronous in nodejs: callback, promises, async/await

1. Callbacks functions

- Callbacks are functions that are passed as arguments to other functions and are executed when the operation completes.

- Callbacks are commonly used to handle asynchronous operations.

const fs = require('fs');
fs.readFile('myfile.txt', function(err, data) {
if (err) {
console.error(err);
} else {
console.log(data.toString());
}
});

* function(err, data): is callback (is the second parameter of readFile() method)

2. Promises

- Promises represent a value that may not be avaiable

const fs = require('fs/promises');

fs.readFile('myfile.txt')
.then((data) => {
console.log(data.toString());
})
.catch((err) => {
console.error(err);
});

* (data) is promises (is return by method readFile())

3. Async/await syntax

- Async/await is a syntax allows to write asynchronous code that looks and behaves like synchronous code

const fs = require('fs/promises');

async function readFile() {
try {
const data = await fs.readFile('myfile.txt');
console.log(data.toString());
} catch (err) {
console.error(err);
}
}

readFile();

Thank you 


 





No comments:

Post a Comment

Golang Advanced Interview Q&A