JavaScript
  • JavaScript Introduction
  • JS Engine
  • V8 Engine
  • First-class function
  • Optimized Code
  • Call Stack & Memory heap
  • Single Thread
  • JavaScript RunTime
  • Nodejs
  • Context and Environment
  • Hoisting
  • Functions
  • Arguments
  • Variables
  • Scope
  • IIFE
  • this
  • call(), apply() and bind()
  • currying
  • Types
  • Type Coercion
  • Functions as Object
  • HOF (Higher Order Function)
  • Two pillars of Javascript
  • Closures
  • Prototypal Inheritance
  • OOP and FP
  • OOP
    • 4 principles of OOP
  • FP
    • Pure function
    • Imperative vs Declarative
    • Immutability
    • HOF and Closures
    • Currying
    • Partial Application
    • Compose and Pipe
  • Composition vs Inheritance
  • OOP vs FP
  • JS working
  • Promises
  • Async Await
  • ES5 - ECMAScript 2009
  • ES6 - ECMAScript 2015
  • ES7 - ECMAScript 2016
  • ES8 - ECMAScript 2017
  • ES9 - ECMAScript 2018
  • ES10 - ECMAScript 2019
  • ES11 - ECMAScript 2020
  • ES12 - ECMAScript 2021
  • JOB Queue
  • Promises Execution
Powered by GitBook
On this page

Was this helpful?

Async Await

It is introduce in ES8, is built on top of Promises.

Async function is a function that returns Promise. The benefit is, it makes code more readable.

The goal of async is to make the code look synchronous, an asynchronous code look synchronous.

Async Await are just promises under neat the hood, we called it syntactic sugar.

EX 1:
async function playerStart() {
    const firstMove = await move(400, 'Left');
    await move(400, 'Right');
    await move(400, 'Up');
    await move(400, 'Down');
}
EX 2:
// Basic usage
fetch('https://jsonplaceholder.typicode.com/users')
    .then(res => res.json())
    .then(console.log);
    
// using ASYNC AWAIT
async function getUsers() {
    const res = await fetch('https://jsonplaceholder.typicode.com/users')
    const data = await res.json();
    console.log(data); // response
}
EX 3:
const urls = [
    'https://jsonplaceholder.typicode.com/users',
    'https://jsonplaceholder.typicode.com/posts',
    'https://jsonplaceholder.typicode.com/albums'
];

// Basic usage
Promise.all(urls.map(url => {
        fetch(url).then(res => res.json());
    }))
    .then(array => {
        console.log('users', array[0]);
        console.log('posts', array[1]);
        console.log('albums', array[2]);
    })
    .catch(console.log);
    
// using ASYNC AWAIT
const getDatas = async function() {
    try {
        const [users, posts, albums] = await Promise.all(urls.map(url => {
            return fetch(url).then(res => res.json());
        }));
        console.log('users', users);
        console.log('posts', posts);
        console.log('albums', albums);
    } catch(err) {
        console.log(err);
    }
}
getDatas();
PreviousPromisesNextES5 - ECMAScript 2009

Last updated 5 years ago

Was this helpful?