Javascript 如何调用异步函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49982058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:32:14  来源:igfitidea点击:

How to call an async function

javascriptnode.jsrequestasync-await

提问by chris

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.

我希望控制台先打印“1”,但我不确定如何调用异步函数并在转到下一行代码之前等待其执行。

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

回答by Taki

according to async_function MDN

根据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.

返回值

一个 Promise,它将使用 async 函数返回的值来解析,或者被从 async 函数中抛出的未捕获异常拒绝。

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

异步函数将始终返回一个承诺,您必须使用.then()await访问它的值

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>

回答by h1b9b

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

您应该await使用异步功能,如果想在继续或使用之前等待它解决.then()

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

or

或者

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

回答by Willem van der Veen

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

async关键字放在函数之前使其成为异步函数。这基本上对函数做了两件事:

  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 awaitkeyword inside this function now. The awaitkeyword 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.
  1. 如果函数没有返回承诺,JS 引擎会将此值包装到已解决的承诺中。因此,该函数将始终返回一个承诺。
  2. 我们现在可以await在这个函数中使用关键字。该await关键字能够“等待”的承诺得到解决。这让我们可以以同步方式编写异步代码。例如本教程

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 asyncfucntions as the name implies also asynchronous. For more on this check out the event loop.

在您的示例中,console.log(2)将始终先完成,因为在 JS 应用程序中,同步代码始终先于异步代码完成。Promises 总是异步的,因此async顾名思义,它也是异步的。有关更多信息,请查看事件循环。