Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
How do I change my code from callback function to promise

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)
   }
})();
about 4 years ago · Juan Pablo Isaza Report

0

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")
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!