Async/await is one of the most revolutionary features that has been added to JavaScript in the past few years. It offers an intuitive replacement to the syntactical mess that promises sometimes tend to be.

There is nothing wrong with the good old Fetch API, which is made available by default to make ajax requests and more.

“The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.” — MDN web docs

A basic fetch request is really simple to set up. Take a look at the following code:


Async/Await 101

Async/await is a relatively new (part of the so-called ECMAScript 2017 JavaScript edition) way to write asynchronous code. Previous alternatives for asynchronous code were callbacks and promises. Async/await is actually just syntactic sugar built on top of promises, and it makes asynchronous code look and behave a little more like synchronous code. Some argue it makes spotting asynchronous code more difficult and might require some getting used to.

It is important to note that theawait keyword cannot be used outside the async function.

Reasons to embrace async/await

  • It makes code concise and clean.
  • It allows us to avoid nesting our code.
  • It makes it possible to handle both synchronous and asynchronous errors with try/catch.
  • It’s much easier to debug (I’m sure I don’t have to tell you to try to figure out where to drop a debugger inside a fetch function).

#ecmascript #nodejs #promises #programming #javascript

Refactoring Fetch to Async/Await
1.65 GEEK