I have read some documentation on async/await and tried coming with an example to understand it better. What I was expecting is that the below code without async and await would print first the string 'Completed', followed by the content of the file. But even after adding async and await, I see that the printing order is unaffected. My impression was async and await usage in this case would print the file contents first followed by the string 'Completed'.
var fs = require('fs');
getTcUserIdFromEmail();
async function getTcUserIdFromEmail( tcUserEmail ) {
let userInfo = {};
let userFound = false;
// Read the file that is containing the information about the active users in Teamcenter.
await fs.readFile('tc_user_list.txt', function(err, data) {
if( err )
console.log( err );
else
console.log( data.toString() );
});
console.log( 'Completed method');
}
Request you to point out what I am doing wrong.
Thanks, Pavan.
awaitdoes? Why are you mixing it and callbacks?fs.readFile()doesn't return a promise. Using filesystem in node.js with async / awaitawaitONLY does anything useful when you await a promise. The regular version offs.readFile()does not return a promise so awaiting it does nothing useful. You can usefs.promises.readFile()and it will return a promise and does NOT accept a callback. The result comes back from the awaited promise, not via a callback.fs.promises.readFile()does NOT accept a callback. Look at the documentation. The result or error comes back in the promise, not in a callback. If you pass it a callback, that callback will NEVER get called. When you program with promises, you get your result or error back in the promise. When you await a promise, you get the result asconst data = await fs.promises.readFile(someFile)and you would catch the error with atry/catch.