0

As a thought experiment and also to deepen my understanding of asynchronous programming, I would like to use the Next.JS getStaticProps method without utilizing aysnc/await syntax. In fact, I would like to do it using only callbacks. I am running into trouble and wondering if this is possible. I'm thinking it must be since async/await is just syntactic sugar for promises, which themselves are syntactic sugar for callback hell, correct? Here is my getStaticProps function:

export function getStaticProps() {
    let products;
    let productPath = path.join(process.cwd(), '/data/products.json')

    // the async call
    fs.readFile(productPath, 'utf-8', (err, data) => {
        if (err) throw err;
        products = JSON.parse(data);

    });
    return {
        props: { products }
    }
}

The return value must be an object with a props property, which itself has the data meant to be passed to page component for rendering. I am lost on how to accomplish this with just callbacks. I know async/await is much more straight forward, but again, I'd like to learn.

madmonkey
  • 73
  • 7
  • "*promises are syntactic sugar for callback hell*" - [not exactly](https://stackoverflow.com/a/22562045/1048572). Your function is not actually returning a promise, and not taking a callback either (which next.js doesn't support) – Bergi May 05 '22 at 08:16
  • async/await is syntatic sugar for promises, that's probably where the confusion comes from. – FINDarkside May 05 '22 at 10:34

1 Answers1

0

You need to return promise since your code is not synchronous. You can do it without await by creating the promise manually:

export function getStaticProps() {
  let productPath = path.join(process.cwd(), '/data/products.json');

  return new Promise((resolve, reject) => {
    fs.readFile(productPath, 'utf-8', (err, data) => {
      if (err) return reject(err);
      const products = JSON.parse(data);
      resolve({
        props: { products },
      });
    });
  });
}

FINDarkside
  • 1,789
  • 1
  • 17
  • 25