Async / Await

Note: 

Behind the scenes it uses the Promise constructor and resolve and reject

but not the then() and catch()

 

Async needs to use the try / catch instead of then() and catch().

function fetchData() {
    return new Promise( ( resolve, reject) => {
        setTimeout(() => {
             resolve("Data has been fetched")
        }, 3000)

    }
}


// Promises
fetchData()
   .then( result => console.log(result) )
   .catch( error => console.log(error) )


// async - await

async function doSomethingAsync() {
   try {
       const result = await fetchData()
       console.log( result )
   } catch {
       console.log(error)
   }

}

doSomethingAsync()

 

function delay(ms) {
    return new Promise( ( resolve, reject) => {
        setTimeout(() => {
             resolve("Data has been fetched")
        }, ms)

    }
}


async function greet() {

    await delay(2000)

    console.log('hello')
}