我一直在浏览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);
Run Code Online (Sandbox Code Playgroud)
控制台输出以下内容(节点v8.6.0):
>外面:[对象承诺]
>里面:嘿那里
为什么函数内部的日志消息会在之后执行?我认为创建async/await的原因是为了使用异步任务执行同步执行.
有没有办法可以使用函数内部返回的值而不使用asyncafter await?
我有节点 14.13.0,即使有--harmony-top-level-await,顶级 await 也不起作用。
$ cat i.js
const l = await Promise.new(r => r("foo"))
console.log(l)
$ node -v
v14.13.0
$ node --harmony-top-level-await i.js
/Users/karel/i.js:1
const l = await Promise.new(r => r("foo"))
^^^^^
SyntaxError: await is only valid in async function
at wrapSafe (internal/modules/cjs/loader.js:1001:16)
at Module._compile (internal/modules/cjs/loader.js:1049:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:791:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?