Joe's
Digital Garden

Javascript

Async

Summarizing the Osberg's tutorial on async Javacript.

  • Non-blocking function calls
  • Javacript in the browser uses an event loop to handle async calls
  • The browser places async work into two queues: microtask and macrotask
  • Promises are placed int othe microtask queue
  • Synchronous code runs first. Event loops after.
  • Promises represent a future value. Either the result of the function call or an error object. They have four possible states, fulfilled, rejected, pending, or settled.

Example promise:

const promise = new Promise((resolve, rject) => {
    if (response.status === 200) {
        resolve(response.body);
    } else {
        const error = {};
        reject(error);
    }
});

promise.then(res => {
    console.log(res);
}).catch(err => {
    console.log(err);
});

The resolve and reject closures are run on success (.then) or failure (.catch).

Async/Await is used to handle an asynchronous function call synchronously.

Example:

const getData = async () => {
    const response = await fetch('https://google.com');
    const data = await response.json()
    console.log(data)
}

getData();

External References

  1. Oseberg, Fredrik Strand. Async Await JavaScript Tutorial - How to Wait for a Function to Finish in Js, freeCodeCamp. Retrieved 2021-01-20.