简体   繁体   中英

Calling await on an async function throws an error

I have this function:

async function fileHash(filename, algorithm = 'md5') {
  return new Promise((resolve, reject) => {
    // Algorithm depends on availability of OpenSSL on platform
    // Another algorithms: 'sha1', 'md5', 'sha256', 'sha512' ...
    let shasum = crypto.createHash(algorithm);
    try {
      let s = fs.ReadStream(filename)
      s.on('data', function (data) {
        shasum.update(data)
      })
      // making digest
      s.on('end', function () {
        const hash = shasum.digest('hex')
        return resolve(hash);
      })
    } catch (error) {
      return reject('calc fail');
    }
  });
}

But when I use: await fileHash(path, 'sha512'); I git this error: await is only valid in async function

Even though the function is an async function.

The problem is not with fileHash , it's with its caller. This

function external() {
    const foo = await fileHash(...someArgs);
}

Won't work. This

async function external() {
    const foo = await fileHash(...someArgs);
}

will.

(OTOH, fileHash itself doesn't need to be async to be await ed. You can even await 2 + 2 ).

You can use await only inside async function, make sure you call it inside other function, declared async. If you call it on top level you have to use.then().catch().

Also, as your function return Promise, you no need to explicitly mark it as async.

A function declared with async always returns a promise. find below code

 async function foo() {

 return "Hello";

   }

 async function display() {

 var message = await foo();

  console.log(message);

  }

  display()

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