How to consume a ‘promise’ with async/await?

Promises using async/await Prior to ES2017, .then() was the way to consume promises.

ES2017  update brings us with a better and easier way to consume promises using  async/await.

Lets see how it works:

Promises using async/await

We start by creating a special kind of function, that is an async function.

This function will basically keep running in the background while performing 

the code that’s inside of it. When the function is done, it automatically returns a promise.

Inside an async function, we can have one or more await statements. await can be put in front of any async promise-based

function to pause your code on that line until the promise fulfills, then return the resulting  Value.

Promises using async/await

Is stopping the code using await, stopping the execution?

No, Stopping execution using an async function is actually not a problem because

this whole function is running asynchronously in the background.

Therefore, it is not blocking the main thread of execution. Here is a simple  example to display the syntax:

Promises using async/await

Let’s look at some real code using async/await:

***

async function my Fetch() {

//returns and stores the promise in response after fetch is complete

let response = await fetch( “ocean. jpg’ );

//if response is NOT fetched successfully

if (!response.ok) {

throw new Error( HTTP error! status: ${response.status}’);

}

Let myBlob = await response.blob( );

let objectURL = URL.create0bjectuRL(my Blob );

Let image = document.createElement(‘img’);

image.src = objectURL;

document. body. appendChild( image );

}

//Calling the function

myFetch()

//.catch() catches the error thrown from myFetch( ), if there is an error

.catch(e => {

console. log( ‘There has been a problem with your fetch operation: ‘ + 

e.message);

});

Leave a Reply

Your email address will not be published.