Phu Ngo
Phu Ngo

Reputation: 61

Using async/await with util.promisify(fs.readFile)?

I'm trying to learn async/await and your feedback would help a lot.

I'm simply using fs.readFile() as a specific example of functions that has not been modernized with Promises and async/await.

(I'm aware of fs.readFileSync() but I want to learn the concepts.)

Is the pattern below an ok pattern? Are there any issues with it?

const fs = require('fs');
const util = require('util');

//promisify converts fs.readFile to a Promised version
const readFilePr = util.promisify(fs.readFile); //returns a Promise which can then be used in async await

async function getFileAsync(filename) {
    try {
        const contents = await readFilePr(filename, 'utf-8'); //put the resolved results of readFilePr into contents
        console.log('✔️ ', filename, 'is successfully read: ', contents);
    }
    catch (err){ //if readFilePr returns errors, we catch it here
        console.error('⛔ We could not read', filename)
        console.error('⛔ This is the error: ', err); 
    }
}

getFileAsync('abc.txt');

Upvotes: 4

Views: 1736

Answers (2)

shallow.alchemy
shallow.alchemy

Reputation: 609

import from fs/promises instead, like this:

const { readFile } = require('fs/promises')

This version returns the promise you are wanting to use and then you don't need to wrap readFile in a promise manually.

Upvotes: 5

tarkh
tarkh

Reputation: 2549

Here is some more ways on using async/await

EDITED: as @jfriend00 pointed in comments, of course you have to use standard NodeJS features with built in methods like fs.readFile. So I changed fs method in the code below to something custom, where you can define your own promise.

// Create your async function manually
const asyncFn = data => {
  // Instead of result, return promise
  return new Promise((resolve, reject) => {
    // Here we have two methods: resolve and reject.
    // To end promise with success, use resolve
    // or reject in opposite
    //
    // Here we do some task that can take time.
    // For example purpose we will emulate it with
    // setTimeout delay of 3 sec.
    setTimeout(() => {
      // After some processing time we done
      // and can resolve promise
      resolve(`Task completed! Result is ${data * data}`);
    }, 3000);
  });
}

// Create function from which we will
// call our asyncFn in chain way
const myFunct = () => {
  console.log(`myFunct: started...`);
  // We will call rf with chain methods
  asyncFn(2)
  // chain error handler
  .catch(error => console.log(error))
  // chain result handler
  .then(data => console.log(`myFunct: log from chain call: ${data}`));
  // Chain call will continue execution
  // here without pause
  console.log(`myFunct: Continue process while chain task still working.`);
}

// Create ASYNC function to use it
// with await
const myFunct2 = async () => {
  console.log(`myFunct2: started...`);
  // Read file and wait for result
  const data = await asyncFn(3);
  // Use your result inline after promise resolved
  console.log(`myFunct2: log from async call: ${data}`);
  console.log(`myFunct2: continue process after async task completed.`);
}

// Run myFunct
myFunct();
myFunct2();

Upvotes: 0

Related Questions