当我运行此代码时:
import fetch from 'node-fetch';
const url = "https://jsonplaceholder.typicode.com/todos/1";
const get = async () => {
try {
let response = await fetch(url);
let res = await response.json();
console.log(res);
} catch (err) {
console.error(err);
}
};
(async function () {
await get();
})();
console.log("I am outside");
我得到以下输出:
$ node index.js
I am outside
{ userId: 1, id: 1, title: 'delectus aut autem', completed: false }
为什么我没有以相反的顺序获得输出,即使我已经在等待异步函数了?
正在等待:
await get()
但是这个不是:
(async function(){
await get()
})();
如果您使用的Node版本支持顶级await
,您可以等待它:
await (async function(){
await get()
})();
或者通过回调来跟进Promise:
(async function(){
await get()
})().then(() => {
console.log('I am outside');
});
或者,您可以将您的逻辑移动到IIFE:
(async function(){
await get();
console.log('I am outside');
})();
这部分是异步
( async function(){
await get()
})();
我可以想出两种方法来首先显示文本;
- 将其移动到异步函数调用之前
- 将其移动到函数调用中
根据我的经验,正如David所说,您应该将要运行的代码放在前面定义的函数作用域中异步代码之后。所有同步超出范围的内容都将首先运行
因为这个函数
( async function(){
await get()
})();
以异步方式运行,因此console.log将首先打印如果你想先运行get()
,你应该做一些类似的事情
( async function() {
await get();
console.log('I am outside')
})
或另一个
( async function() {
await get();
}).then( () => {
console.log('I am outside');
})