Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

javascript - 'await Unexpected identifier' on Node.js 7.5

I am experimenting with the await keyword in Node.js. I have this test script:

"use strict";
function x() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve({a:42});
    },100);
  });
}
await x();

But when I run it in node I get

await x();
      ^
SyntaxError: Unexpected identifier

whether I run it with node or node --harmony-async-await or in the Node.js 'repl' on my Mac with Node.js 7.5 or Node.js 8 (nightly build).

Oddly, the same code works in the Runkit JavaScript notebook environment: https://runkit.com/glynnbird/58a2eb23aad2bb0014ea614b

What am I doing wrong?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Thanks to the other commenters and some other research await can only be used in an async function e.g.

async function x() {
  var obj = await new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve({a:42});
    },100);
  });
  return obj;
}

I could then use this function as a Promise e.g.

x().then(console.log)

or in another async function.

Confusingly, the Node.js repl doesn't allow you to do

await x();

where as the RunKit notebook environment does.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...