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

440
Visualizações
Exceljs await not working in promise in async function

Im currently working on opening and writing on an excel file using exceljs. However, the await is making an error

SyntaxError: await is only valid in async functions and the top level bodies of modules

Despite the function being in async. How can I resolve this problem? The following is the code that I am using

async function Process(filename){
  const workbook = new ExcelJS.Workbook();

  let myPromise = new Promise(function(myResolve, myReject) {
    // "Producing Code" (May take some time)
    try{
      await workbook.xlsx.readFile(filename)
      myResolve(); // when successful
    }catch(err){
      myReject();  // when error
    }

  });

  // "Consuming Code" (Must wait for a fulfilled Promise)
  myPromise.then(
    function() {
        /* code if successful */ 
    },
    function() {return false;}
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Agreeing with the comments, you should avoid the Promise constructor antipattern and never use await in the executor of a new Promise!

You should write either

function Process(filename){
  const workbook = new ExcelJS.Workbook();
  
  // "Producing Code" (May take some time)
  let myPromise =  workbook.xlsx.readFile(filename);

  // "Consuming Code"
  return myPromise.then(function() {
    /* code if successful, waiting for a fulfilled Promise */
    return …;
  }, function() {
    /* code when error, waiting for a rejected Promise */
    return false;
  });
}

or

async function Process(filename){
  const workbook = new ExcelJS.Workbook();

  try {
    // "Producing Code" (May take some time)
    await workbook.xlsx.readFile(filename);

    // "Consuming Code" (wait for the promise to be fulfilled)
    return …;
  } catch(err) {
    // Code when error in producing or consuming code
    return false;
  }
}
about 4 years ago · Juan Pablo Isaza 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