链接承诺与当时和捕获 [英] Chaining promises with then and catch

查看:109
本文介绍了链接承诺与当时和捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用蓝鸟Promise库。我想链接承诺并捕捉特定的承诺错误。这就是我正在做的事情:

I'm using the bluebird Promise library. I'd like to chain promises and catch specific promises errors. Here's what I'm doing :

getSession(sessionId)
  .catch(function (err) {
    next(new Error('session not found'));
  })
  .then(function (session) {
    return getUser(session.user_id);
  })
  .catch(function (err) {
    next(new Error('user not found'));
  })
  .then(function (user) {
    req.user = user;
    next();
  });

但是如果 getSession 引发错误,调用两个 catch ,以及第二个然后。我想在第一个 catch 停止错误传播,这样第二个 catch 只在<当$ getUser 成功时,code> getUser 抛出,第二个然后。怎么办?

But if an error is thrown by getSession, the two catch are called, as well as the second then. I'd like to stop the error propagation at the first catch, so that the second catch is only called when getUser throws, and the second then when getUser succeeds. What do?

推荐答案

.catch 返回的承诺方法仍将通过回调的结果解决,它不仅仅停止链的传播。您将需要分支链:

The promise that is returned by the .catch method will still be resolved with the result of the callback, it doesn't just stop the propagation of the chain. You will either need to branch the chain:

var session = getSession(sessionId);
session.catch(function (err) { next(new Error('session not found')); });
var user = session.get("user_id").then(getUser);
user.catch(function (err) { next(new Error('user not found')); })
user.then(function (user) {
    req.user = user;
    next();
});

或使用第二个回调然后

getSession(sessionId).then(function(session) {
    getUser(session.user_id).then(function (user) {
        req.user = user;
        next();
    }, function (err) {
        next(new Error('user not found'));
    });
}, function (err) {
    next(new Error('session not found'));
});






或者,更好的方法是传播链中的错误,只在最后调用 next

getSession(sessionId).catch(function (err) {
    throw new Error('session not found'));
}).then(function(session) {
    return getUser(session.user_id).catch(function (err) {
        throw new Error('user not found'));
    })
}).then(function (user) {
    req.user = user;
    return null;
}).then(next, next);

这篇关于链接承诺与当时和捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆