How to call an async function

63,760

Solution 1

according to async_function MDN

Return value

A Promise which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.

async function will always return a promise and you have to use .then() or await to access its value

async function getHtml() {
  const request = await $.get('https://jsonplaceholder.typicode.com/posts/1')  
  return request
}

getHtml()
  .then((data) => { console.log('1')})
  .then(() => { console.log('2')});
  
// OR 

(async() => {
  console.log('1')
  await getHtml()  
  console.log('2')
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Solution 2

You should await the async function, if want to wait for it to resolve before continuing or use .then()

await getHtml();
console.log('2');

or

getHtml()
 .then(() => {
    console.log('2');
 });

Solution 3

Putting the async keyword before a function makes it an asynchronous function. This basically does 2 things to the function:

  1. If a function doesn't return a promise the JS engine will wrap this value into a resolved promise. Thus, the function will always return a promise.
  2. We can use the await keyword inside this function now. The await keyword makes it possible to 'wait' for a promise to be resolved. Which lets us write asynchronous code in a synchronous way. For example this tutorial.

In your example the console.log(2) will always finish first because in a JS application always the synchronous code will finish first before the asynchronous code. Promises are always asynchronous and thus are async fucntions as the name implies also asynchronous. For more on this check out the event loop.

Share:
63,760
chris
Author by

chris

Updated on July 13, 2021

Comments

  • chris
    chris almost 3 years

    I want the console to print '1' first, but I am not sure how to call async functions and wait for its execution before going to the next line of code.

    const request = require('request');
    
    async function getHtml() 
    {
        await request('https://google.com/', function (error, response, body) {
        console.log('1');
      });
    
    }
    
    getHtml();
    console.log('2');
    

    Of course, the output I'm getting is

    2
    1
    
  • balu
    balu over 2 years
    Regarding the first suggestion: Using await in the main scope / global scope is a syntax error.
  • user21398
    user21398 over 2 years
    To circumvent this, you could use a top-level await by changing your Js file ext to .jsm and type='module' in your html script tag
  • Bill Gardner
    Bill Gardner about 2 years
    Thanks for posting the tutorial, that's actually what got me over my particular issue.