当我将我的代码转换为异步等待时,我需要将我的函数转换为异步,但我在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-file‘
我的另一个功能是检查文件是否存在,如果删除
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发布于 2018-11-01 11:43:54
异步函数应该返回一个promise。
如果您的代码不打算返回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
}
});
}发布于 2018-11-01 11:54:53
你只需要把上面的代码包装在一个异步函数中,因为await在异步函数中是有效的。喜欢,
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);
}
} https://stackoverflow.com/questions/53090138
复制相似问题