Asynchronous JavaScript Headaches

Whenever I'm building something and I come across a scenario where I need to get something from my database I typically use the async await pattern but I've never really understood it.

I typically use the async await thing and log my response, then I see some promise thing logged onto my response, then I introduce a try catch block. Sometimes that solves my problems, but today that didn't solve my problem. Typically I wrangle a mix of async functions to get it to work somehow but lord knows that if someone asked me to explain what's going on, I would not have a clue.

So today I decided to learn about these things.

I started with the web.dev article "JavaScript Promises: an introduction"  but honestly my brain just refused to understand what was being talked about. The example in the "What's all the fuss about?" section just didn't sink.

Eventually I ended up reading the You Don't Know JS series. I started with the Async & Perfomance book. Then that mentioned closures and so I went to the soft introduction of closures in the book Up & Going. Then came back to the book Async & Performance.

I started with Chapter 1 of Asynchrony: Now & Later and that had things that I understood and other things that I really struggled to understand and left the fuck alone. It gives some context on callbacks and hopefully now I'm able to understand callbacks and then promises and hopefully I can get my programs to work well.

Especially the concurrency and parallelism bit. That really flew over my head

Eventually, I gave up on the "deep learning" bit of this with the hope that sometime in the near future I'm able to learn how to use the async await pattern.

For now, I learnt how to use promises and that seems to give me a predictable way of working with promise objects once they are resolved my code now has a lot of this:

function createTransaction(transactionObject) {
  return new Promise(async (resolve, reject) => {
    try {
      let response = await fetch(
        `.../api/...`,
        {
          method: 'post',
          body: JSON.stringify({
            ...transactionObject,
          }),
        }
      );
      resolve(response.json());
    } catch (error) {
      reject(error);
    }
  });
}

once defined the function is then used like this:

      createTransaction(transactionObject).then((result1) => {
        // do something with result1
      });

It works, and I'm able to meet my deadline. Win-win.