我已经阅读了async/await,在阅读了几篇文章之后,我决定自己测试一下。然而,我似乎不明白为什么这行不通:

async function main() {  
    var value = await Promise.resolve('Hey there');
    console.log('inside: ' + value);
    return value;
}

var text = main();  
console.log('outside: ' + text);

控制台输出以下内容(节点v8.6.0):

> outside: [object Promise] > inside:嘿,大家好

为什么函数内部的日志消息之后执行?我认为创建async/await的原因是为了使用异步任务执行同步执行。

是否有一种方法可以使用函数内部返回的值,而不使用main()后的.then() ?


当前回答

我喜欢这种聪明的语法来从入口点执行异步工作

void async function main() {
  await doSomeWork()
  await doMoreWork()
}()

其他回答

顶级等待已经转移到阶段3阶段4(见namo的评论),所以你的问题的答案是我如何在顶级使用async/await ?就是使用await:

const text = await Promise.resolve('Hey there');
console.log('outside: ' + text)

如果你想要main()函数:在main()调用中添加await:

async function main() {
    var value = await Promise.resolve('Hey there');
    console.log('inside: ' + value);
    return value;
}

var text = await main();  
console.log('outside: ' + text)

兼容性

v8自2019年10月起 Chrome DevTools, Node.js和Safari web检查器中的REPL 标志后面的节点v13.3+——harmony-top-level-await TypeScript 3.8+(发行) Deno自2019年10月起 Webpack@v5.0.0-alpha.15

现在使用ECMAScript22,我们可以在顶级模块中使用await。

这是一个使用(await顶层)的例子:

const response = await fetch("...");
console.log(response):

另一个没有(await顶层)的示例

  async function callApi() {
    const response = await fetch("...");
    console.log(response)      
}
callApi()

因为main()是异步运行的,所以它返回一个承诺。你必须在then()方法中获取结果。因为then()也返回promise,所以必须调用process.exit()来结束程序。

main()
   .then(
      (text) => { console.log('outside: ' + text) },
      (err)  => { console.log(err) }
   )
   .then(() => { process.exit() } )

如果您的唯一目标是为了测试目的控制混合了其他代码的异步代码的执行顺序,那么您可以将整个顶级代码包装在定义为异步函数的立即调用函数表达式(IIFE)中。在问题的示例中,在调用main()之前添加await。

当您的代码不在异步函数中或不在模块的顶层主体中时,可以使用此模式。换句话说,如果你只是在一个js文件中测试一堆代码,并使用Live Server、RunJs或任何其他类型的JavaScript工具来观察控制台窗口,将所有代码包装在定义为异步的IIFE中,当你想在执行下一行之前等待异步代码完成时,使用await关键字。

let topLevelIIFE = (async () => { 异步函数main() { var value = await承诺。解决('嘿'); Console.log ('inside: ' + value); 返回值; } Var文本=等待main(); Console.log ('outside: ' + text); }) ()

在Chrome DevTools或其他行为类似的浏览器REPL工具的REPL中运行IIFE主体中指定的代码时,您不需要使用此模式。

你需要在package.json中添加类型 “类型”:“模块” 你可以出发了。 从'axios'导入axios; Const res = await axios.get('https://api.github.com/users/wesbos'); console.log (res.data);

记住,如果你改变了文档的类型,那么你必须以ES6的方式编写代码。