【问题标题】:'await Unexpected identifier' on Node.js 7.5Node.js 7.5 上的“等待意外标识符”
【发布时间】:2017-07-02 16:52:36
【问题描述】:

我正在 Node.js 中尝试使用 await 关键字。我有这个测试脚本:

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

但是当我在节点中运行它时,我得到了

await x();
      ^
SyntaxError: Unexpected identifier

我是使用nodenode --harmony-async-await 运行它,还是使用Node.js 7.5 或Node.js 8(夜间构建)在我的Mac 上的Node.js 'repl' 中运行它。

奇怪的是,同样的代码在 Runkit JavaScript notebook 环境中工作:https://runkit.com/glynnbird/58a2eb23aad2bb0014ea614b

我做错了什么?

【问题讨论】:

  • 您只能在async functions 内部使用await
  • 我不确定你是否可以在async 函数之外使用await,但我可能错了。

标签: javascript node.js asynchronous


【解决方案1】:

感谢其他评论者和其他一些研究 await 只能用于 async 函数,例如

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

然后我可以将此函数用作 Promise,例如

x().then(console.log)

或在另一个异步函数中。

令人困惑的是,Node.js repl 不允许您这样做

await x();

RunKit 笔记本环境的作用。

【讨论】:

  • x 声明为async 毫无意义。只要有一个正常的功能,并像你最初一样拥有return 的承诺,它更短,更高效,并且具有完全相同的结果。
  • 在 Haskell 中,他们称之为异步单子
  • 是的,回调很棘手。 Async/Await 也有点棘手。你需要等待一切或什么都没有(类似的东西)。因此,您必须在每个本质上是异步的函数调用上显式键入 async 和 await。
  • 如果将在下面使用,那么使用异步有什么意义?如果我们可以在下面使用 await,我会理解的。
【解决方案2】:

正如其他人所说,您不能在异步函数之外调用“等待”。 但是,要解决这个问题,您可以包装 await x();在异步函数调用中。即,

function x() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve({a:42});
    },100);
  });
}
//Shorter Version of x():
var x = () => new Promise((res,rej)=>setTimeout(() => res({a:42}),100));

(async ()=>{
    try{
      var result = await x();
      console.log(result);
    }catch(e){
      console.log(e)
    }
})();

这应该在 Node 7.5 或更高版本中工作。也适用于 chrome canary sn-ps 区域。

【讨论】:

    【解决方案3】:

    所以正如其他人所建议的那样,await 将在异步中工作。所以你可以使用下面的代码来避免使用then:

    async function callX() {
        let x_value = await x();
        console.log(x_value);
    }
    
    callX();
    

    【讨论】:

    • 谢谢,也忘记了异步。错误应该是“Unexpected token await”,因为是不能使用的await...
    猜你喜欢
    • 2017-11-24
    • 2018-04-08
    • 2017-06-19
    • 2012-09-23
    • 2017-10-11
    • 1970-01-01
    • 2018-01-17
    • 2015-09-14
    相关资源
    最近更新 更多