0

I am trying to get folder size of a directory in Node.js, but it runs the last line as Undefined first and then log the size in the callback function. It works if I put the last line of the code in a setTimeout function with a few seconds delay...

const getSize = require('get-folder-size');
let folderSize;

getSize(folder, (err, size) => {
   folderSize = size;
   console.log(size);
});

console.log(folderSize);

Is there a way to get the result from the callback first and then get the result of the last line of the code?

Also, is there a sleep() to pause between codes like wscript.sleep(sec) in VBScript? I googled but couldn't find what I want.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Charles
  • 9
  • 2
  • Relevant (not an exact duplicate, though): https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – AKX Apr 12 '21 at 12:12

1 Answers1

1

In classic Node.js, you'd write the rest of your code inside that callback (or likely you'd call another function there), but it leads to long callback pyramids and hard-to-read code. Luckily, promises are a thing, and async/await gives us a nice syntax for them.

You can promisify the getSize function and await the result in an async function:

const { promisify } = require("util");
const getSizeP = promisify(require("get-folder-size"));

async function main() {
  const size = await getSize(folder);
  console.log(size);
}

main();

As for the second sneaky question: The callback-based delay/sleep function is setTimeout; it's not hard to formulate a promise-based version:

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

You can then await delay(100) to your heart's content.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • AKX, Thanks for your answer. If I do console.log of the result after main() call, it still makes error as undefined because it is Asynchronous function. My question is that it completely waits code until it gets the size of the folder before proceeding next codes as Synchronous. Also, for the second answer about delay(), I get error as 'await is only valid in async functions and the top level bodies of modules'. appreciate your time. – Charles Apr 12 '21 at 22:43
  • Yes – you'd write your code within the asynchronous `main()` since top-level async/await is not yet widely enabled. – AKX Apr 13 '21 at 06:51