Javascript Async/Await And Promises

Code Snippets AsyncAwait And Promises
Share:

About

In this code snippet, we’ll learn about async/await and promises in Javascript.

Promises allow us to execute code asynchronously(file operations, api calls, blocking code, …). When we make a promise we define what code it will execute. When it’s done the then() function is used to execute any further code(process results from the promise).

Async and await keywords make working with promises easier. If any value is returned from an async function it will be returned as a promise which can be awaited with the await keyword. 

Note: Await can only be used within an async function.

Let’s see the code examples below.

Code:

Promise

//Calling the function that will return a promise.
//This will start executing the code in the promise.
//When it's finally done the code in then() will run. 
authenticate("Bob", "password123").then(
  function(response) {
  	//On success execute this code.
  	console.log(response);
    
    //do authenticated stuff here...
  },
  function(error) {
  	//If error occours log it.
  	console.log("Authentication failed: " + error);
  }
);

//We'll wrap our promise in a function.
//This way we can easily call it and pass it parameters.
function authenticate(username, password){
	return new Promise(function(success, error) {
  	//Here we do our work...//////////
    
    const authenticted = callBackendAuthService(username, password);
    
    /////////////////////////////////
    
    //When done...
    if(authenticted) 
      success("you are now authenticated.");
    else 
      error("username or password incorect");
  });
}

function callBackendAuthService(username, password){
	//Lets pretend this is our backend...
  if(username == "Bob" && password == "password123")
  	return true;
  
  return false;
}

Resulting output:

Async/Await

//Async keyword./////////////////////////////////////////////////

//If a function is marked as async it will return a promise.
async function generateRandomNumber() {
  return Math.ceil(Math.random()*10);
}

//The promise can be then handled with then() like so:
generateRandomNumber().then(
  function(result) {
    console.log(result);
  }
);

////////////////////////////////////////////////////////////////

//Await keyword/////////////////////////////////////////////////

GetRandomNumber();

async function GetRandomNumber(){
	//await can be used to await the result from a promise instead of using then().
  //await can only be used within a function marked as async.
  let randomNumber = await generateRandomNumber();
  console.log(randomNumber);
}

////////////////////////////////////////////////////////////////

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger