如何调用异步函数

时间:2018-04-23 13:13:46

标签: javascript node.js request async-await

我希望控制台能够打印' 1'首先,但我不知道如何在进入下一行代码之前调用异步函数并等待其执行。

const request = require('request');

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

}

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

当然,我得到的输出是

2
1

3 个答案:

答案 0 :(得分:10)

根据async_function MDN

  

返回值

     

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

异步函数将始终返回一个承诺,您必须使用.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>

答案 1 :(得分:1)

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

  1. 如果函数没有返回一个promise,JS引擎会将此值包装到已解析的promise中。因此,该函数将始终返回一个承诺。
  2. 我们现在可以在此功能中使用await关键字。 await关键字可以让您等待&#39;希望得到解决。这让我们以同步方式编写异步代码。例如this tutorial
  3. 在您的示例中,console.log(2)将始终首先完成,因为在JS应用程序中,同步代码始终在异步代码之前完成。 Promise总是异步的,因此是async函数,因为名称暗示也是异步的。有关详细信息,请查看the event loop.

答案 2 :(得分:0)

你应该qq_duck = Duck("QQ") I've decided to change my name into QQ . So please call me QQ from now on! Quack! I've decided to change my name into QQ . So please call me QQ from now on! Quack! I've decided to change my name into QQ . So please call me QQ from now on! Quack! ... Traceback (most recent call last): File "<input>", line 1, in <module> File "<input>", line 3, in __init__ File "<input>", line 13, in name File "<input>", line 13, in name File "<input>", line 13, in name [Previous line repeated 488 more times] File "<input>", line 11, in name RecursionError: maximum recursion depth exceeded while calling a Python object async函数,如果想在继续使用之前等待它解决或使用await

.then()

await getHtml();
console.log('2');
相关问题