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

183
Views
Why is my Async Await not working in NodeJS?

Trying to perform a basic async/await in NodeJS but it is still going out of order.

Code I am trying to run:

var fs = require('fs');
var stringData;

async function find(context) {
  try {
    let text = await readFile('./sql/test.sql', context);
  } catch (e) {
    console.log('Try/Catch Error: ' + e)
  }

  console.log('display')
  console.log('display ' + JSON.stringify(text))
  return
}

async function readFile(file, context) {
  new Promise((resolve) => {
    fs.readFile(file, (error, data) => {
        if (error) {
          throw error;
        }
        stringData = data.toString()
      }),
      (err) => {
        console.log('ERROR: ' + JSON.stringify(err));
      }, () => {
        resolve(1);
      }
  })
};

module.exports.find = find;

When I run the above I get an undefined results for the console.log for text.

I am expecting text to use the await to populate before moving down to the console logs.

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

0

Looks like you are not resolving the promise with the result you get from data.toString(); you need to add resolve(stringData)

PS. In the error handler you are using resolve, you should probably be using reject there

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!