Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript REST APIs with Express Managing Data and Asynchronous Code Async/Await in Express

erkany
erkany
7,189 Points

Why we can't use async/await directly in getQuotes in records.js?

Like below;

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

I am not quite sure what you're trying to achieve here, and what isn't working.

2 Answers

I don't see why you can't write this function with async/await.

require('fs').promises;

async function getQuotes() {
  try {
    const data = await fs.promises.readFile('data.json', 'utf8');
    return JSON.parse(data);
  } catch (err) {
    console.error(err.message);
    // whatever else you want to do here
  }
}

Based on my research since node 11 something you can use the fs.promises module to use asynchronous file system functions that return promises rather than using callbacks. Check out the docs here

The reason for not using async/await inside the getRecords functions is that the idea is to mimic the return of data from a database. getRecords() is trying to replicate the action of getting the records from a database so the function does not return the data immediately.