Home » vue » Promise return pending not the value inside a function using async/await [duplicate]

Promise return pending not the value inside a function using async/await [duplicate]

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a code to read files’ paths from a directory, and return them.
i use async/await to call the function to do this, but i got Promise pending not the target value.

function readdirAsync(path) {
  return new Promise((resolve, reject) => {
    fs.readdir(path, (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
  }).then(res => {
    const versions = res.map(filename => match(/^[\d]+(\.+\d+)+/g, filename)[0]);
    return versions;
  });
}

async function getVersions() {
  const final = await readdirAsync(require('path').join('src/versions/'));
  return final;
}



const versionsList = getVersions().then(res => res);
console.log(versionsList); 
Answers:

await only waits for a promise to resolve inside an asyncronous function.

getVersions is an async function, so it returns a promise (which, when it resolves, resolves with the value final).

const versionsList = getVersions().then(res => res);

You aren’t awaiting here (and can’t, because you aren’t in an async function), so you get the return value of the then() method … which is the promise.