首页 > 解决方案 > 将 2 个调用转换为异步函数时出现问题,因此我可以使用异步等待

问题描述

当我将我的代码转换为异步等待时,我需要将我的函数转换为异步,但我遇到了 2 的问题。第一个是从我的文件中获取哈希的直接函数。

const getHash = async (file_to_hash) =>
{
md5File(file_to_hash,(err, hash) => 
{
    if (err) throw err
    return hash

}
)}

当我通过

 const hash2 = await fh.getHash(newPath +'\\' + origFile.recordset[0].upload_id  + '.' + origFile.recordset[0].orig_file_type)

我明白了

const hash2 = await fh.getHash(newPath +'\\' + origFile.recordset[0].upload_id  + '.' + origFile.recordset[0].orig_file_type)
                      ^^^^^

SyntaxError: await is only valid in async function

我正在使用“md5 文件”

我拥有的另一个功能是检查文件是否存在以及是否删除它

const deleteFile = async (path) => {
fs.exists(path, function(exists) {
    if(exists) {
      fs.unlink(path)
      return true

   } else {
 return false
   }
  })
}

调用它时出现以下错误

var delSuccess = await fh.deleteFile(tmpFile)    
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function

标签: node.js

解决方案


异步函数应该返回一个承诺。

如果你的代码不会返回一个 Promise,你需要将它包装在一个 Promise 中。

const myFunc = async () => {
  return await new Promise((resolve, reject) => {
    // write your non async code here
    // resolve() or reject()
  })
}

如果您的代码返回一个 promise 调用,只需使用 await 将其返回即可。

const deleteFile = async (path) => {
  return await fs.exists(path);
}

或者有时你可能想从回调中返回一个承诺,

const deleteFile = async (path) => {
  return await new Promise((resolve, reject) => {
    fs.exists(path, function(exists) {
      if(exists) {
        await fs.unlink(path)
        resolve(true);
      } else {
        resolve(false); // or you can reject
      }
  });
}

推荐阅读