【问题标题】:NodeJS - Unexpected identifier awaitNodeJS - 意外的标识符等待
【发布时间】:2018-04-08 17:09:39
【问题描述】:

我使用 NodeJS 并尝试通过 async/await 包装我的代码,但每次都收到“SyntaxError: Unexpected identifier”错误。这是我的代码:

async function showOff(phone) {
    return new Promise((resolve, reject) => {
        var message = 'Hey friend, I have a new ' + phone.color + ' ' + phone.brand + ' phone';
        resolve(message);
    });
};

let message = await showOff({ color: "black", brand: "Sony" });

有什么问题?

【问题讨论】:

标签: javascript async-await


【解决方案1】:

await 只能在 async 函数内使用。

function showOff(phone) {
  return new Promise((resolve, reject) => {
    var message = 'Hey friend, I have a new ' + phone.color + ' ' + phone.brand + ' phone';
    resolve(message);
  });
};

async function phone() {
  let message = await showOff({ color: "black", brand: "Sony" });
  console.log(message);
}

phone();

async 表示等待响应的函数,而不是执行异步操作的函数。

【讨论】:

    【解决方案2】:

    来自文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

    await 运算符用于等待 Promise。 只能在异步函数中使用。

    所以你可以简单地将所有代码包装在一个匿名 aync 函数中

    (async () => {
        async function showOff(phone) {
            return new Promise((resolve, reject) => {
                var message = 'Hey friend, I have a new ' + phone.color + ' ' + phone.brand + ' phone';
                resolve(message);
            });
        };
    
        let message = await showOff({ color: "black", brand: "Sony" });
    
        console.log(message);
    })();
    

    在某些情况下,这可能是一个简单的解决方案

    【讨论】:

      猜你喜欢
      • 2017-07-02
      • 2017-06-19
      • 2017-11-24
      • 1970-01-01
      • 2018-07-19
      • 2012-12-27
      • 2018-01-17
      • 1970-01-01
      相关资源
      最近更新 更多