Tf11
Tf11

Reputation: 93

How to set variable = a value from a function result inside async function

Inside a function, I would like to set the value of a variable (foldersInDir) to the results of getting the contents of a directory using fs.readdir();

I thought using await would force the console.log line to wait for a response, but it's not.

How can I set foldersInDir = the return value?

/*Begin function*/
const listContents = async (myPath) => {

    var fs = require('fs');

    let foldersInDir = await fs.readdir(myPath, function(err, items) {
        console.log(items); //works
        return  items;
    });

    console.log(foldersInDir); //does not work, undefined

}

Upvotes: 4

Views: 1090

Answers (4)

risingfire
risingfire

Reputation: 19

Edit: sorry, need to promisify() the function

const fs = require('fs');
const { promisify } = require('util') // available in node v8 onwards
const readdir = promisify(fs.readdir)

async function listContents() {
  try {                                         // wrap in try-catch in lieu of .then().catch() syntax
    const foldersInDir = await readdir(myPath)  // call promised function
    console.log('OK, folders:', foldersInDir)   // success
  } catch (e) {
    console.log('FAIL reading dir:', e)         // fail
  }  
}

listContents('path/to/folder') // run test

Upvotes: 1

Danilo Lemes
Danilo Lemes

Reputation: 2488

const fs = require('fs');

const test = () => {
        let folders = fs.readdirSync('.');
        return folders;
}

console.log(test());

Upvotes: 1

Behrooz
Behrooz

Reputation: 2371

I recommend using the promisify function provided by Node.js to fix the problem. This function will convert a callback-based function to a promise-based function, which can then be used using the await keyword.

const fs = require('fs');
const {
  promisify
} = require('util');

const readdirAsync = promisify(fs.readdir);

/*Begin function*/
const listContents = async(myPath) => {
  let foldersInDir = await readdirAsync(myPath);

  console.log(foldersInDir);
}

Upvotes: 0

bredikhin
bredikhin

Reputation: 9025

You need to convert readdir to a promise, e.g.:

const foldersPromised = (path) =>
  new Promise((resolve, reject) =>
    fs.readdir(path, (err, items) =>
      err !== undefined ? reject(err) : resolve(items)
    )
  );
try {
  let foldersInDir = await foldersPromised(myPath);
} catch(err) {
  console.log(err);
}

Upvotes: 1

Related Questions