DEV Community

Cover image for JS Bites: Chapter 3 - Async/Await vs Promise
Sanjay R
Sanjay R

Posted on • Updated on

JS Bites: Chapter 3 - Async/Await vs Promise

In promise, if you remember there will be a Promise Creator the one who creates the promise and the one who receives those promises and does operations on them. 

what if we can synchronously write the asynchronous code? instead of nesting code.

Here comes the async and await…

function getData(){
    return new Promise(...)
}

const result = getData(); //this will return the promise not the actual data
Enter fullscreen mode Exit fullscreen mode

JS thinks this is the Synchronous operation and doesn't wait for the function async operation unless we put await

const result  = await getData()
console.log(result)

//but this will be an error because 
//await is only valid in async functions and the top-level bodies of modules
Enter fullscreen mode Exit fullscreen mode

correct code is,

function getData(){
  return new Promise(res=>{
    setTimeout(function() {res("hi")}, 1000);
  })
}

async function start(){
  const result  = await getData()
  console.log(result)
}

start()
Enter fullscreen mode Exit fullscreen mode

wrap the await in the async function

Async/Await code vs Promise code

these two functions do the same work, but which one do you prefer, obviously the first one because that is simple.

Important points in async/await

  • Async and Await must be used together.
  • Await can be used without async with JavaScript modules & Chrome DevTools Console.
  • Async and Await only affect the Promise receiver
  • Any function can be converted to an async
  • All async function returns a promise by default.
  • Error Handling try/catch

Error Handling try/catch

function getData(a,b){
  return new Promise((resolve,reject)=>{
    setTimeout(function() {
      if(a*b<=10){
        resolve("less than 10")
      }else{
        reject("this is less than 10")
      }
     }, 2000);
  })
}

async function start(a,b){
  try{
    const result  = await getData(a,b)
    console.log(result)
  }catch(error){
    console.log(`error ${error}`)
  }
}

start(2,10)
Enter fullscreen mode Exit fullscreen mode

Conclusion
Why use async/await?

It makes code more readable and enables the writing of code that uses asynchronous functions but looks like synchronous code. 

Comment your thoughts…

See you in the next Chapter…

Top comments (0)