简体   繁体   中英

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

I have some sample code I'm trying to run, and I want some asynchronous function that is executing to be called synchronously. I know you need to add async to the function in order to have an await. I've already done that. Still though I get the following error:

  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)

For context here is my code:


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

Why am I getting said error when my function is already async?

You are trying to use async-await inside a function that is not marked with async (your callback).

Just make your callback an async-await function.

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; the above statement reside within new Promise callback handler which is again a anonymous function.

So, one has to put async against with this function as well as it associated with new scope which is nothing a new promise object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM