我怎样才能在顶层使用asynchronous/等待?

我一直在asynchronous/等待,经过几篇文章,我决定自己testing一下。 然而,我似乎无法绕过我的头为什么这是行不通的:

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):

>外:[object promise]

>里面:嘿,那里

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

有没有办法可以使用函数内返回的值,而不使用main()后面的.then() main()

我似乎无法包围我的头为什么这是行不通的。

因为main回报一个承诺; 所有的asyncfunction。

在顶层,您必须使用从不拒绝的顶级async函数,如下所示:

 (async () => { try { var text = await main(); console.log(text); } catch (e) { // Deal with the fact the chain failed } })(); 

注意一下; 您必须处理承诺拒绝/asynchronousexception。 如果你愿意的话,你可以通过catch函数(而不是try / catch语法)来调用它。

 (async () => { var text = await main(); console.log(text); })().catch(e => { // Deal with the fact the chain failed }); 

…这是一个更简洁一点。

或者使用then catch

 main() .then(text => { console.log(text); }) .catch(err => { // Deal with the fact the chain failed }); 

…或两个参数then

 main().then( text => { console.log(text); }, err => { // Deal with the fact the chain failed } ); 

再次注意我们正在注册一个拒绝处理程序。