DEV Community 👩‍💻👨‍💻

Cover image for Async patterns in node js
Grace Valerie Anyango
Grace Valerie Anyango

Posted on

Async patterns in node js

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')
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  1. 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)
Enter fullscreen mode Exit fullscreen mode

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)
   }
}

Enter fullscreen mode Exit fullscreen mode
  1. Async / Await A method in which the parent method is declared with the async keyword and inside it await keyword is permitted.

Top comments (0)

Image description

Join the One Year Club

You can earn this badge by being a registered member of the DEV Community for at least one year. Create an account and get started today.