Simplest async await example in JavaScript

The word “async” before a function means one simple thing: a function always returns a promise. 

Often considered complex our async functions can be simple also, for instance, this function returns a resolved promise with the result of 1; let’s test it:

async function f1() {
    return 1;
  }
  
  f1().then(alert);  

In above method, first f1() function is called, then f1() returns value 1, as 1 is not an error so it is passed to the resolve method ie. alert

In next method we will try console.log method.

async function f1() {
    return 1;
  }
  
  f1().then(console.log);

//output will be 1 as "1" is passed to the console.log() method

In next example we will pass nothing in the console.log() method to see whther the value “1” was actually passed or not.

 

async function f1() {
    return 1;
  }
  
  f1().then(console.log());

//output is blank as nothing is passed to the console.log() method
 

Leave a Reply

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