Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
149 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...