Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

386
Visualizações
'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?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

As others have said, you can't call 'await' outside of an async function. However, to get around this you can wrap the await x(); in an async function call. I.e.,

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)
    }
})();

This should work in Node 7.5 or above. Also works in chrome canary snippets area.

over 4 years ago · Santiago Trujillo Relatório

0

so as suggested by others await will work inside async. So you can use the below code to avoid using then:

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

callX();
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda