Async patterns in node js
Grace Valerie Anyango
Posted on December 30, 2021
A code in node js should be nonblocking to avoid halting the execution of lines of code ahead of it. Implementing functionality that could take time is done asynchronously in order to take the execution part of that function out of the main loop.
There are three asynchronous patterns:
1. Callbacks
A callback is a function that is passed as an argument to another function and should be invoked whenever the asynchronous work is finished.
const { readFile } = require('fs')
console.log('start of program')
readFile('./myFile.txt', 'utf-8', (err, myfile) => {
if(err) {
console.log(err)
return
}
console.log(myFile)
})
console.log('End of program')
the readfile function is asynchronous and therefore the program will move on to the next instruction while the function continues to run in the background.
The output is as follows:
start of program
End of program
content inside the text file myFile
- Promises The promise object represents the eventual completion of async operations, regardless of the results(success or failure). It is also defined as a proxy for a value not necessarily known at the time it is created.
const { readFile } = require('fs')
const readMyFile = (path) => new Promise((resolve, reject) => {
readFile(path, 'utf-8', (err, context) => {
if (err) {
console.log(err)
return
}
else {
console.log(context)
}
})
})
readMyFile('./files/myFile.txt')
.then((result) => console.log(result)
.catch((err) => console.log(err)
A promise can exist in either one of these states:
Pending - this is the initial state where it is neither resolved or rejected.
Fulfilled - The promise will be in this state if the operation has been completed successfully.
Rejected - the state when the operation has failed.
Promisify
This function is defined in Node's util module as a standard and its goal is to convert callback to promise.
const { readFile } = require('fs')
const util = require('util')
const readMyFile = util.promisify(readFile)
async function start() {
try {
const myText = await readMyFile('./myFile', 'utf-8')
console.log(myText)
}
catch (error) {
console.log(error)
}
}
- Async / Await A method in which the parent method is declared with the async keyword and inside it await keyword is permitted.
Posted on December 30, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.