0
    await fs.mkdir(path.join(__dirname, "/smartsheet_download"), 
   { recursive: true }, (err) => { 
     if (err) { 
       return console.error(err); 
     } 
     __dirname= path.join(__dirname, "/smartsheet_download");
   console.log("after func:" + __dirname);
   })

   console.log("this must be printed after path at last")
}

my question in this above function is i am printing "this must be printed after path at last" after the fs.mkdir operation but when i am running the code it prints first. i am using async and await so that it must wait for fs.mkdir to complete the execution before printing the last line. Still this thing does not work. Could u please tell how can i wait for fs.mkdir to complete and then pass the execution to next line. moreover, please tell why await do not work here?

2
  • async await doesnt work on callbacks, it works on promises witch you havent Commented Jun 18, 2020 at 6:57
  • also there is `mkdirSync´ for synchronous purpose Commented Jun 18, 2020 at 6:59

1 Answer 1

1

your logic is correct. however, if you look at the signature of fs.mikdir it returns void

export function mkdir(path: PathLike, options: MakeDirectoryOptions & { recursive: true }, callback: (err: NodeJS.ErrnoException | null, path: string) => void): void; <---

which means, it cannot be awaited, although it executes an async task, but due it returns void, it cannot be awaited.

the callback exists for when you need to know if the what happend to the operation, succesed/faild something like that, thats why your log happens before, because mkdir returns void.

so if you need do something after fs.mikdir was finished. you can use fs.mkdirSync which will block execution of code untill the call has finsished, or just do your work in the callback you pass to the function

fs.mkdir(path.join(__dirname, "/smartsheet_download"), 
   { recursive: true }, (err) => { 
     if (err) { 
       return console.error(err); 
     } 
     __dirname= path.join(__dirname, "/smartsheet_download");
   console.log("after func:" + __dirname);

 console.log("this must be printed after path at last")
   })



Sign up to request clarification or add additional context in comments.

3 Comments

hi i used mkdirSync but , it stop using the callback given inside the mkdir. could you please help ? so i can assume that if i use mkdirSync it will always create the directory first then pass the control to next line?
since mikdirSync stops execution of code, then there is no need for the callback, the lines after the call to mikdirSync will be executed if and only if the mikdirSync call was successful
Thanks a lot for help!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.