Ad

How To Write An Alternate Function Of Util.promisify In Node Js?

I want to explore util.promisify in nodejs. My below code fetch the data from files and also print for util.promisify which is now comment. I started to write my own function similar to promise which wait for the data either from db or file and then return the data. But I am getting empty string instead of data in my console.log.

I am new to node js. I want to use this in my important project which fetch data from db.

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

function read(file){
    var str="";
    setTimeout(()=>{
        fs.readFile(file,(err,data)=>{
            str=data;
        })
    },2000);
    return new Promise((resolve,reject)=>{
        resolve(str);
    });
}



//const read=util.promisify(fs.readFile);

let promiseArr=[read('/promise/data1.txt'),read('/promise/data1.txt'),read('/promise/data1.txt')];

async function main(){
    let [data1,data2,data3]=await Promise.all(promiseArr);
    console.log(data1.toString());
    console.log(data2.toString());
    console.log(data3.toString());
}

main();

Ad

Answer

A simple explanation of how util.promisfy works can be found here: https://medium.com/@suyashmohan/util-promisify-in-node-js-v8-d07ef4ea8c53

function read(file) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      fs.readFile(file, (err, data) => {
        if (err) reject(err);
        resolve(data);
      });
    }, 2000);
  })
}
Ad
source: stackoverflow.com
Ad