Hello World. We are WEB cult. We make a note for web developers.

Only await the result not the asynchronous function itself

Written or Updated on August 26, 2022 🖋️

When you use await for calling API, better use await to wait for the result to be finished, don’t wait for the API function itself.

Normal pattern

Let’s say there is an API that takes a second to return the result.

const api = (n) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      return resolve(`reult: ${n}`)
    }, 1000)
  })
}

When you want to do something with the results of three API calls, you end up waiting for 3 seconds.

const myFunc = async () => {
  
  const s = new Date()
  
  const result1 = await api(1)
  const result2 = await api(2)
  const result3 = await api(3)
  
  const e = new Date()
  
  // Do something with results
  
  console.log(`it took ${e - s}ms`)
}
Result

myFunc() // it took 3004ms

Use await for Promise

Promise<pending> will be assigned to the variable If you don’t use await. Using await to wait for the Promise to finish, rather than waiting for each API function, we can reduce the time until all the APIs finish.

const betterFunc = async () => {
  
  const s = new Date()
  
  const result1 = api(1)
  const result2 = api(2)
  const result3 = api(3)
  
  await result1
  await result2
  await result3
  
  const e = new Date()
  
  // Do something with results
  
  console.log(`it took ${e - s}ms`)
}
結果 

betterFunc() // it took 1001ms

You can see that the original function took a total of 3 seconds to execute, but now it takes only 1 second. This is because the three APIs that take one second to process are executed in parallel. It is a small thing, but it is a good trick to shorten the time required for processing.

By the way, since Javascript is single-threaded, it is not executed at exactly the same time, but is switched sequentially to act as if it is being processed at the same time.