MegaRoks
MegaRoks

Reputation: 948

The function does not work synchronously, although I specified async / await

I want to read all the JSON files from the data folder. I use the library https://www.npmjs.com/package/node-dir. I got a function, but it does not work synchronously. Variable replacements renders undefined.

async function giveHtml() {
    let replacements = await dir.readFiles(__dirname + '/data', { match: /.json$/ }, (err, content, next) => {
        if (err) {
            throw err
        }
        next()
    })
    console.log(replacements)
    return replacements
}

What's my mistake?

Upvotes: 0

Views: 70

Answers (4)

red-X
red-X

Reputation: 5128

dir.readFiles does not seem to return a promise, it returns undefined so that's what you're getting in return. You can try creating your own promise like this.

function giveHtml() {
  return new Promise((resolve, reject) => {
    dir.readFiles(__dirname + '/data', { match: /.json$/ }, (err, content, next) => {
      if (err) {
        return reject(err)
      }
      // do stuff per file if you want
      next()
    }, (err, files) => {
      if (err) {
        return reject(err)
      }
      resolve(files)
    })
  })
}

Upvotes: 1

wlh
wlh

Reputation: 3515

async/await is syntactic sugar for a JavaScript Promise. await is listening for a resolved promise. In the npm package you are using, the readFiles function works with a callback, not a promise.

Use the promiseFiles function call instead: https://www.npmjs.com/package/node-dir#promisefiles-dir-callback-

Upvotes: 0

Quentin
Quentin

Reputation: 943211

You can only await a promise, and dir.readFiles does not return a promise.

You can either convert it to use a promise or use a module that already returns a promise.

Upvotes: 4

filo
filo

Reputation: 36

I think that your mistake is about not waiting for the response; You are returning the var replacements before the answer is given.

I'd try to call

console.log(replacements) 

after your

next()

Upvotes: 0

Related Questions