gpt4 book ai didi

javascript - 如何调用异步函数?

转载 作者:数据小太阳 更新时间:2023-10-29 04:30:41 25 4
gpt4 key购买 nike

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

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 函数总是返回一个 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>

关于javascript - 如何调用异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49982058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com