Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Asynchronous Code in Express Asynchronous Code in Express Refactor Using Async/Await

Vitaly Khe
Vitaly Khe
7,160 Points

Why refactoring getQuotes to async/await doesn't work?

const getQuotes = async () =>  fileSystem.readFile('data.json', 'utf8', (err, data) => {
        if (err) {
             return err;
        }
        else {
            const quotes = JSON.parse(data);
            return quotes;
        }
    });

(async () => {
    const q = await getQuotes();
    console.log( q);
})();

Console:

Promise { undefined }

2 Answers

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,696 Points

The readFile method doesn't return anything. If you have a function that takes a callback, and you want it to return a promise, one strategy is to wrap it in a Promise constructor, which takes a function with two arguments, resolve and reject. You can call resolve() on the successful response and reject() on the error.

const getQuotes = () =>  {
    return new Promise((resolve, reject) => {
        fileSystem.readFile('data.json', 'utf8', (err, data) => {
            if (err) {
                 return reject(err);
            } else {
                const quotes = JSON.parse(data);
                return resolve(quotes);
            }
        })
    })
}

You can also use a neat utility function called promisify

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree
karan Badhwar
Web Development Techdegree Student 12,996 Points

Hey Brendan Whiting, sorry to post a question to your answer so late. But she said transform the getUsers function into a promise if it wasn't one, if we add async in front of the function, then again why do we need to return a Promise, if it's gonna do that for us?