如何从fs.unlink返回承诺
我想删除文件,并等待删除在向前推进之前成功。我已经在承诺中使用了UNINK函数来获得结果,但是如果成功完成Unlin链接后,如果删除文件时有任何错误的纠结,我将从承诺中获得结果,承诺不会返回任何错误。
服务:
public removeUserImage(
user: User,
): Promise<NodeJS.ErrnoException | boolean> {
const pathToRemoveImage = 'src/public/uploads'+ '/' + user.image_url;
return new Promise((resolve, reject) => {
unlink(pathToRemoveImage, (error) => {
if (error) reject(error);
resolve(true);
});
});
}
控制器:
const isFileRemoved = await this._userService.removeUserImage(user);
//This block not excuting
if (!isFileRemoved) {
throw new InternalServerErrorException(
'Error occurred while trying to remove file.',
);
}
I want to delete a file and wait for the deletion to succeed before moving forward. I have used unlink function inside a promise to get the result, but when unlink done successfully then I am getting the result from the promise if there is any kink of error while deleting the file the promise does not return any error.
Service:
public removeUserImage(
user: User,
): Promise<NodeJS.ErrnoException | boolean> {
const pathToRemoveImage = 'src/public/uploads'+ '/' + user.image_url;
return new Promise((resolve, reject) => {
unlink(pathToRemoveImage, (error) => {
if (error) reject(error);
resolve(true);
});
});
}
Controller:
const isFileRemoved = await this._userService.removeUserImage(user);
//This block not excuting
if (!isFileRemoved) {
throw new InternalServerErrorException(
'Error occurred while trying to remove file.',
);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果有错误,您的承诺拒绝。当使用
等待
时,您需要将代码包装在try..catch
中以处理任何故障,您可以(并且应该)使用承诺 api
fs
函数的api如果您希望您的方法始终始终解决与布尔人,你想要类似的东西
Your promise rejects if there's an error. When using
await
, you need to wrap the code intry..catch
in order to handle any failuresFYI, you can (and should) use the Promises API versions of the
fs
functionsIf you wanted your method to always resolve with a Boolean, you'd want something like
使用旧
fs
软件包的版本:使用如下:
Version using old
fs
package:Use as following:
错误将始终用于捕获块,
建议:您不需要将Unlink(回调)转换为Prome FS也具有承诺功能,请检查 this
The error will always go to catch block,
Suggestion: You don't need to convert unlink(callback) to promise fs has promise function also, check this