0

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); 
Sumurai8
  • 20,333
  • 11
  • 66
  • 100
Zeyad Etman
  • 2,250
  • 5
  • 25
  • 42
  • getVersions().then(res => console.log(res)); try this. – Arup Rakshit Aug 12 '18 at 20:00
  • It works fine, but i need to set `versionsList` to `res` – Zeyad Etman Aug 12 '18 at 20:05
  • @ZeyadEtman I have rolled back your last edit, because you should not change an existing question in such a way that it invalidates answers that have already been given. If you believe your question is not a duplicate, you can edit your question to explain how your question differs. If you have additional follow-up questions based on this question and answers given, you can ask a new question and link this question in it. You may be able to find an answer to some or all of those questions by searching around on stackoverflow, or by examining the related questions when asking one. – Sumurai8 Aug 12 '18 at 21:31

1 Answers1

2

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335