我正在尝试进行 DELETE
调用,并且正在执行以下功能。我知道在一个 promise 中,需要有一个“解决”和一个“拒绝”状态,但我收到一个未处理的 promise 拒绝错误:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): [object Object]
我真的不喜欢在 promise 中使用条件语句,因为它会变得困惑,但我在这里要做的是检查组织是否经过验证,如果是,则不应执行删除操作,并且会拒绝。
function deleteOrg(id) {
return new Promise((resolve, reject) => {
// A helper function that returns an 'org' object
findById(id)
.then((orgObject) => {
if (orgObject.verified_at !== null) {
throw new Error(422, 'Unable to delete organization')
}
//Organization is not verified, so proceed to delete
new Organization().where({'id': id}).destroy()
.then(() => {
return resolve() //return 200 upon deletion
})
.catch((err) => {
return reject(new Error(500, 'Unable to delete organization'))
})
})
.catch((err) => {
const m = `Unable to delete organization: ${err.message}`
return reject(new Error(500, m))
})
})
}
我很确定我正在处理 if
错误的拒绝。
最佳答案
因为 findById 和 .destroy 返回 Promise,所以不需要 Promise 构造函数
然后您的代码被简化为
function deleteOrg(id) {
return findById(id)
.then((orgObject) => {
if (orgObject.verified_at !== null) {
throw new Error(422, 'Unable to delete organization')
}
//Organization is not verified, so proceed to delete
return new Organization().where({'id': id}).destroy()
.catch((err) => {
throw (new Error(500, `Unable to delete organization: ${err.message}`));
});
});
}
关于javascript - Node.js 中未处理的 promise 拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41752855/