6 points you need to know about async/await in JavaScript

Yaser Adel Mehraban on August 18, 2019

If you have faced a code like below, then this article will help you in multiple ways 😁. fetchPizzas() .then((pizzas) => { return sortByTop... [Read Full]
markdown guide
 

I’m not sure why the first block of code in the article uses promises like the old callback hell, but here it is the proper way to write that first block of code:

fetchPizzas()
  .then( sortByToppings )
  .then( checkDeliveryOptions )
  .then( checkBirthdayGift )
  .then( sendToCustomer ); 

And, in my opinion, it looks better then the alternatives offered by the article, not mentioning the testability of it.

 

Agree, I think promises are better that async/await when it comes to function composition.

 
 

Thanks for the post Yaser!

One thing I'd add is that although we don't have top-level await, it's most likely going to happen as it's at Stage 3.

GitHub logo tc39 / proposal-top-level-await

top-level `await` proposal for ECMAScript (stage 3)

ECMAScript proposal: Top-level await

Champion: Myles Borins

Status: Stage 3

Synopsis

Top-level await enables modules to act as big async functions: With top-level await, ECMAScript Modules (ESM) can await resources, causing other modules who import them to wait before they start evaluating their body.

Motivation

Limitations on IIAFEs

With await only available within async functions, a module can include an await in the code that executes at startup by factoring that code into an async function:

// awaiting.mjs
import { process } from "./some-module.mjs"
let output
async function main() {
  const dynamic = await import(computedModuleSpecifier)
  const data = await fetch(url);
  output = process(dynamic.default, data);
}
main();
export { output };

This pattern can also be immediately invoked. You could call this an Immediately Invoked Async Function Expression (IIAFE), as a play on IIFE idiom.

// awaiting.mjs
import
 

Updated the post to reflect this, thanks again Nick

 

Thanks for sharing, didn't know about this 👌🏽

 

Great article Yaser! btw: AsyncFuncton -> AsyncFunction

 

Nice catch, I should double check my spell checker in VS Code

 

Good read, but I believe next to last code line should be ‘deliver()’. Also, looking for more on thenable, any good coverage somewhere? Thanks!!

 
 
code of conduct - report abuse