DEV Community

Cover image for (Javascript) My learning journey: Async / Await
Eric The Coder
Eric The Coder

Posted on • Updated on

(Javascript) My learning journey: Async / Await

An essential point to remember a training course is to take notes and discuss the subject with others. That's why every day I will post on dev.to the concepts and notes that I learned the day before.

If you want to miss nothing click follow and you are welcome to comments and discuss with me.

Without further ado here is a summary of my notes for today.

Synchronous vs Asynchronous

Synchronous code is executed line by line. Each line of code always wait for the previous line to finish before executing the next one. So obviously, the problem is that long running operation will block code execution.

Asynchronous code is executed after a task that run in the background finish. ex. the call back function that will be execute after a setTimeout(). Asynchronous is non-blocking so dont wait for other task to finish.

One example of asynchronous in js is Ajax (Asynchronous, javascript and XML). What Ajax do? Ajax request some data from a web server dynamically (without reloading the page)

Ajax request in js where done with the XMLHttpRequest() function and data was mostly in XML format. Now in 2021 people mostly use the fetch() API and the data are mostly in JSON format (Javascript object notation)

Modern async function like fetch() return a Promise. aka, a container/placeholder for future result. The future result/value is the response from the Ajax (fetch) call.

// Example of a fetch API returning a Promise
const request = fetch('http://example.com/api/cats')

// request return a Promise
console.log(request) // Promise {<pending>}
Enter fullscreen mode Exit fullscreen mode

A Promise is pending until it is settled (finish). It can have two settled sate: fulfilled (success) or rejected (error).

// Example of a fetch API returning a Promise
const getCatsImage = function() {
  // the fetch API return a Promise
  // When the promise is fullfilled the then function execute with the request response as the parameter.
  const request = fetch('http://example.com/api/cats')
    .then(response => return response.json())
    .then(data => loadCatImage(data[0]))
  })
}
Enter fullscreen mode Exit fullscreen mode

Handling Promise error

const getCatsImage = function() {
  // the fetch API return a Promise
  // When the promise is fullfilled the then function execute with the request response as the parameter.
  const request = fetch('http://example.com/api/cats')
    .then(response => return response.json())
    .then(data => loadCatImage(data[0]))
    .catch(err => console.log(err))
    .finally(() => console.log('Run after both')
  })
}
Enter fullscreen mode Exit fullscreen mode

Create a Promise

const wait = function(sec) {
  return new Promise(function(resolve, reject) {
    setTimeout(() => {
      resolve('wait over')
    }, sec * 1000)
  })
}

wait(3).then((msg) => console.log(msg)) // wait over
Enter fullscreen mode Exit fullscreen mode

Async / Await
The async function and the await keyword were introduced as an extension to promises. They were introduced to make promise-based asynchronous programming more readable. Async/await just simplifies the syntax used to consume Promise.

// async keyword run the function in asynchronous mode 
// and return a Promise
const delay = async function(sec) {
  // await pauses the async function block of code 
  // until the promise returns a value
  const response = await new Promise(function(resolve, reject) {
     setTimeout(() => {
      resolve('wait over')
    }, sec * 1000)
  })
  console.log(response)
}

delay(3)
Enter fullscreen mode Exit fullscreen mode

Catch error in async/await

const delay = async function(sec) {
  try {
    const response = await new Promise(function(resolve, reject) {
      setTimeout(() => {
        resolve('wait over')
      }, sec * 1000)
    })
    console.log(response)
  } catch(err) {
    console.log(err.message)
    // You can also throw error up to calling parent
    throw err
  }
}
delay(3)

Enter fullscreen mode Exit fullscreen mode

The await keyword can only be use in a async function. So to use await in the main module you have to create a IIFE
function (Immediately Invoked Function Expression)

(async function() {
  const cats = await getCats()
  console.log('start')
  console.log(cats)
  console.log('end')
})()
Enter fullscreen mode Exit fullscreen mode

Or use the then keyword

console.log('start')
getCats().then(cats => {
    console.log(cats)
    console.log('end')
}
Enter fullscreen mode Exit fullscreen mode

Running Promises in Parallel

(async function() {
  // const cats = await getCats()
  // const dogs = await getDogs()
  // use Promise.all to run in Parallel 
  const data = await Promise.all([getCats(), getDogs()])
  console.log('start')
  // Promise.All return an array
  console.log(data[0]) //cats
  console.log(data[1]) //dogs
  console.log('end')
})()
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
moniruzzamansaikat profile image
Moniruzzaman Saikat

pretty nice...
Just cleared some of my concepts. Which course did you take?