如何调用异步函数

克里斯 :

我希望控制台首先打印“ 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
这样:

根据async_function MDN

返回值

一个Promise,它将由async函数返回的值来解决,或者被async函数中引发的未捕获的异常拒绝。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章