0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
user68288
  • 702
  • 2
  • 6
  • 27
  • 1
    `readFile` don't return a promise afaik. You probably want to look at [fsPromises.readFile](https://nodejs.org/api/fs.html#fspromisesreadfilepath-options) instead. I think they're relatively new so you might want to check on your node version. – Andy Feb 22 '22 at 20:40
  • @Andy That's why it's wrapped in `new Promise()` – Barmar Feb 22 '22 at 20:41
  • Probably relevant: [How to read file with async/await properly?](https://stackoverflow.com/q/46867517) – VLAZ Feb 22 '22 at 20:42
  • Oh, ok, got confused that the OP had used a _function_ called `readFile` too. @Barmar. I think it was still a good suggestion regardless. – Andy Feb 22 '22 at 20:42
  • 1
    Indeed. Now Node has built-in promise aware fs functions, rolling your own is just a chance to make mistakes. – Quentin Feb 22 '22 at 20:44

1 Answers1

1

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

BrendanMullins
  • 587
  • 3
  • 18