Node.js中未处理的promise拒绝

kqqjbcuj  于 2023-10-17  发布在  Node.js
关注(0)|答案(4)|浏览(124)

我正在尝试调用DELETE并实现下面的函数。我知道在promise中,需要有一个“resolve”和一个“reject”状态,但是我得到了一个未处理的promise rejection错误:
UnhandledPromiseRejection警告:未处理的promise拒绝(拒绝id:1):[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中的拒绝是错误的。

oyjwcjzk

oyjwcjzk1#

由于findById和.destroy返回Promises,因此不需要Promsie构造函数
然后,您的代码将被简化为

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}`));
        });
    });    
}
r9f1avp5

r9f1avp52#

在promise构造函数中创建promise是一个known anti-pattern。尝试将promise模块化为单独的函数:

function deleteOrg(id) {

  const verifyOrg = (orgObject) => {
    if (orgObject.verified_at !== null) {
      throw new Error(422, 'Unable to delete organization')
    }
  };

  const destroyOrg = () => new Organization().where({
    'id': id
  }).destroy();

  return findById(id)
    .then(verifyOrg)
    .then(destroyOrg);
}

在这里,你可以让错误通过promise链传播,并在外部处理它们:

deleteOrg(id)
  .catch((err) => {
    const m = `Unable to delete organization: ${err.message}`;
    // ...
  });
laximzn5

laximzn53#

original method() => {
             try{ //code to raise the exceptio

            })

;
最好的处理方法是使用expect,它可以与异常匹配。被检体检查

someMock.mockFunc(() => {
          throw new Error("Something");
        });

   test('MockFunc in error', () => {
     return expect(orginalCall()).rejects.toMatch('Something');
   });
xzlaal3s

xzlaal3s4#

我实际上遇到了同样的问题,因为我没有将return关键字添加到调用方法(deletetetype(id))中。添加return后,UnhandledPromiseRejectionWarning消失。

function deleteOrg(id)
{
// actually returns a promise 
}

return deleteOrg.then((result) => { 
   //code logic after deleting the record// 
});

相关问题