Promise 最佳实践:Promise.resolve(false) 或 Promise.reject()



我有一个函数可以检查某些东西并返回一个承诺,并且有一个函数是授权的调用它。我可以通过两种方式使用它:

// Way A: resolve() or reject()
export const existsA = (id) => {
    return getSomethingById(id)
        .then((result) => {
            if (!result ) {
                return Promise.reject(new Error(''));
            }
            return Promise.resolve();
        })
        .catch(error => Promise.reject(new Error(error)));
};
exports.isAuthorizedA = (req, res, next) => {
    existsA(req.user.id)
        .then(next)
        .catch(next(Boom.forbidden()));
};
// Way B: resolve(true) or resolve(false)
export const existsB = (id) => {
    return getSomethingById(id)
        .then((result) => {
            if (!result ) {
                return Promise.resolve(false);
            }
            return Promise.resolve(true);
        })
        .catch(error => Promise.reject(new Error(error)));
};
exports.isAuthorizedB = (req, res, next) => {
    existsB(req.user.id)
        .then((result) => (result ? next() : next(Boom.forbidden())))
        .catch(next(Boom.forbidden()));
};

哪种方式是正确的?提前谢谢你。

最佳做法是拒绝任何错误发生(未捕获的异常(的承诺,这样最好是

const existsA = (id) => getSomethingById(id);
const isAuthorizedA = (req, res, next) => {
    existsA(req.user.id)
        .then(next)
        .catch(next(Boom.forbidden()));
};

在getSomethingById((中处理所有失败的情况,并从那里拒绝错误。如果你想要 null 或任何虚假值作为错误,然后写

getSomethingById(id) => {
  new Promise(function(resolve, reject) {
  // your operations    
  if(!value)
    reject(new Error('your code'))
  else
    resolve(123)
});

至于你的用例,你不希望结果是假的,我的意思是有时在你的承诺中,你期望一个假的结果是积极的,比如跟随

checkIfPostIsLiked(userId, postId)
.then(isLiked => {
    if (isLiked) return unLikePost(userId, postId)
    return likePost(userId, postId)
})
.catch(next(Boom.forbidden()));

如果您将 false 视为错误,那么这可能不起作用。

因此,作为最佳实践,每当您想抛出错误或将该情况标记为失败情况时,请始终拒绝承诺并在 catch 块中处理它。

无需拒绝错误或解决结果,这就足够了:

export const existsA = (id) => {
  return getSomethingById(id)
    .then(result => result != null);
};

任何未捕获的异常都将被拒绝。

最新更新