0

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.

7
  • What do you think await does? Why are you mixing it and callbacks? Commented May 24, 2020 at 5:37
  • 1
    fs.readFile() doesn't return a promise. Using filesystem in node.js with async / await Commented May 24, 2020 at 5:38
  • 1
    await ONLY does anything useful when you await a promise. The regular version of fs.readFile() does not return a promise so awaiting it does nothing useful. You can use fs.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. Commented May 24, 2020 at 5:41
  • @GuyIncognito It works using fs.promises as mentioned in the other thread. Thanks. Commented May 24, 2020 at 5:45
  • 1
    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 as const data = await fs.promises.readFile(someFile) and you would catch the error with a try/catch. Commented May 24, 2020 at 5:51

1 Answer 1

2

await only works if the expression being awaited returns a Promise. fs.readFile does not return a promise, so right now your await doesn't do anything.

Luckily for us, node provides a function fs.promises.readFile that is like fs.readFile but instead of expecting a callback, returns a promise.

const fs = require('fs')

Now you can await fs.promises.readFile(...)

getTcUserIdFromEmail(); // > contents_of_tc_user_list
                        //   Completed method

async function getTcUserIdFromEmail( tcUserEmail ) {
    let userInfo = {};
    let userFound = false;
    const data = await fs.promises.readFile('tc_user_list.txt')
    console.log(data.toString())
    console.log( 'Completed method');
}
Sign up to request clarification or add additional context in comments.

5 Comments

No need to promisify fs.readFile() when fs.promises.readFile() is already there. Also, you need to show that calling getTcUserIdFromEmail() itself needs to use await or .then() to know when it's done because it returns a promise too.
@jfriend00 Pardon me, but from what I understand, for every async method, the caller of the async method should have to 'await' it. This is because there is no callback. Is this understanding correct.
If you just want to see the log messages, you don't have to await getTcUserIdFromEmail(). Your node process will exit when all the async stuff resolves. You absolutely have to await if you want to use the return value of getTcUserIdFromEmail(), however
@jfriend00 I didn't know about fs.promises, I will update my answer to use that, thank you!
@PavanDittakavi - If you want to know when an asynchronous function that returns a promise is done or if it had errors, you have to use await with try/catch around it or or .then() and/or .catch().

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.