Node.js 将2个调用转换为异步函数时出现问题,因此我可以使用async Wait
当我将代码转换为Async Await时,我需要将函数转换为Async,但我在使用2时遇到了问题。第一个是从我的文件中获取散列的直接函数Node.js 将2个调用转换为异步函数时出现问题,因此我可以使用async Wait,node.js,Node.js,当我将代码转换为Async Await时,我需要将函数转换为Async,但我在使用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 +'\
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
异步函数应该返回一个承诺
const myFunc = async () => {
return await new Promise((resolve, reject) => {
// write your non async code here
// resolve() or reject()
})
}
如果您的代码不打算返回承诺,则需要将其封装在承诺中
const myFunc = async () => {
return await new Promise((resolve, reject) => {
// write your non async code here
// resolve() or reject()
})
}
如果您的代码返回承诺调用,只需使用wait返回它
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
}
});
}
您只需要将上述代码封装在异步函数中,因为wait在异步函数中是有效的。像
async function_name()=> {
try{
let hash2 = await fh.deleteFile(newPath +'\\' +
origFile.recordset[0].upload_id + '.' + origFile.recordset[0].orig_file_type)
} catch(err){
console.log('Error is: ', err);
}
}
你可能应该仔细阅读。将回调样式的异步调用映射到
async
函数中是行不通的。另外,不要检查文件是否存在,并期望unlink()
成功无误。这会导致.iffs.exists
已经返回了一个承诺
,您不需要返回等待
,也不需要将其包装在异步
函数中。此外,执行返回等待几乎总是一个坏主意。只需返回承诺
本身,并让调用代码的等待它。