node.js - 将 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
解决方案
异步函数应该返回一个承诺。
如果你的代码不会返回一个 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
}
});
}
推荐阅读
- r - 接收错误“美学必须是长度1或与数据相同(9420):颜色”在R
- google-analytics - Google Analytics:哪些事件将用户引导至最终事件
- domain-driven-design - DDD 实体工厂职责
- c# - 文件上传没有图像路径可以保存到服务器
- javascript - 在 electrons-js 应用程序中使用“Cast Service”
- java - 在 Spring Tools Suite 中调试单个 Java 类
- go - 是否可以从 golang 工具(即不是测试)获取覆盖信息?
- reactjs - React-native:维护多个过滤器按钮/多个过滤器的状态
- apache-spark - 如何确定火花集群的基础设施需求
- java - 使用 Spring Kafka 框架时如何处理错误/异常?