Exceljs 等待在异步函数中无法正常工作

Exceljs await not working in promise in async function

我目前正在使用 exceljs 打开和写入 excel 文件。 但是,await 出错了

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

尽管函数处于异步状态。我该如何解决这个问题? 以下是我使用的代码

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

同意评论,你应该避免 Promise constructor antipattern and !

你应该写任何一个

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

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