簡體   English   中英

即使在Node.js中的異步函數中,如何解決“等待僅在異步函數中有效”的問題?

[英]How to fix “await is only valid in async function” even when await is in an async function in Node.js?

我有一些示例代碼正在嘗試運行,並且我希望同步執行一些正在執行的異步函數。 我知道您需要將異步添加到函數中以便進行等待。 我已經做到了。 雖然我得到以下錯誤:

  let result = await promise;
               ^^^^^

SyntaxError: await is only valid in async function
    at new Script (vm.js:80:7)
    at createScript (vm.js:274:10)
    at Object.runInThisContext (vm.js:326:10)
    at Module._compile (internal/modules/cjs/loader.js:664:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)

對於上下文,這是我的代碼:


async function main() {
  var client = Client.fromConnectionString(deviceConnectionString, Protocol);
  fs.stat(filePath, function (err, fileStats) {
  var fileStream = fs.createReadStream(filePath);

  for (var i=0;i<10;i++) {

    let promise = new Promise((res, rej) => {
      client.uploadToBlob('testblob.txt', fileStream, fileStats.size, function (err, result) {
        if (err) {
          console.error('error uploading file: ' + err.constructor.name + ': ' + err.message);
        } else {
          console.log('Upload successful - ' + result);
        }
        res(i);
      });
    })
    let result = await promise;
    console.log(result);
  }

  fileStream.destroy();
  });
}

main();

當我的函數已經異步時,為什么會出現錯誤提示?

您正在嘗試在未標記異步(您的回調)的函數內使用異步等待。

只需將您的回調設為異步等待函數即可。

async function main() {
  var client = Client.fromConnectionString(deviceConnectionString, Protocol);
  fs.stat(filePath, async function (err, fileStats) {
  var fileStream = fs.createReadStream(filePath);

  for (var i=0;i<10;i++) {

    let promise = new Promise((res, rej) => {
      client.uploadToBlob('testblob.txt', fileStream, fileStats.size, function (err, result) {
        if (err) {
          console.error('error uploading file: ' + err.constructor.name + ': ' + err.message);
        } else {
          console.log('Upload successful - ' + result);
        }
        res(i);
      });
    })
    let result = await promise;
    console.log(result);
  }

  fileStream.destroy();
  });
}

main();

let result = await promise; 上面的語句位於新的Promise回調處理程序中,該處理程序又是一個匿名函數。

因此,必須對此功能以及與新作用域相關聯的異步操作,而這並不是一個新的promise對象。

let promise = new Promise(async (res, rej) => {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM