Home > Enterprise >  How do I change my code from callback function to promise
How do I change my code from callback function to promise

Time:10-27

I have a code like this below. The code still use callback function and i want to change using promise. I hesistate how to change them. can you help how change it


const fs = require('fs')

fs.readdir('/', (err, result) => {
  if (err) {
    throw new Error(err.message)
  }
  console.log(result)
})

CodePudding user response:

fs.readdir('/') is already promise, you need to resolve it either with chaining like you did or with syntax sugare using async/await inside IIFE

(async () => {
   try{
        const result = await fs.readdir('/');
        console.log(result)
   }catch(err){
      console.log(err.message)
   }
})();

CodePudding user response:

Provided that you import asycronous version of readdir() which is located in require('fs').promises you can read directories asyncronouly

const fs = require('fs').promises

const asyncReadDir = async(dirName) => {
    try {
         const dirData = await fs.readdir(dirName)
         console.log("Read successfully")
         // other code here
    } catch(error){
         // catch errors
         console.log(error)
    }
}

asyncReadDir("/downloads")
  • Related