如何在NodeJS中使用我当前编码中的promise链接

时间:2016-03-16 09:11:22

标签: javascript node.js promise

我是NodeJS的新手,以下是我的编码,你们可以了解编码的目的是什么。我的代码检查器告诉我,使用promise chaining,当我使用它时,可以在链的末尾使用单个.catch()。请通过使用promise chaining告诉我如何转换当前的编码。

jobSeekerService.findJobSeekerUserByEmail(user.username).then(function (jsFromDb) {
    if (jsFromDb) {
        jobAlertsService.findJobAlertWithCategoriesByJobSeekerId(jsFromDb.jobSeeker.id).then(function (subscription) {
            if (subscription.categories && subscription.categories != 0) {
                res.redirect(redirectUrl);
            } else {
                res.redirect('/subscriptions');
            }
        }, function (err) {
            winston.error('applications.controller findJobAlertWithCategoriesByJobSeekerId : %s', err);
            res.send(500);
        });
    } else {
        res.redirect(redirectUrl);
    }
}, function (err) {
    winston.error('applications.controller findJobSeekerUserByEmail : %s', err);
    res.send(500);
});

2 个答案:

答案 0 :(得分:1)

你可以/应该使用这样的承诺

promise.then(function(res) {
  /* do whatever you want with the res */
  return promise2(foo);
}).then(function(data) {
  /* data from promise2 are here */
}).catch(function(err) {
  /* err parameter contains error from reject() */
});

您可以无限次使用.then(),但catch()只能调用一次以进行错误处理(它将包含来自reject()中相应Promise()的错误对象

编辑这个例子以便更好地理解。

答案 1 :(得分:1)

您可以使用

jobSeekerService.findJobSeekerUserByEmail(user.username).then(function (jsFromDb) {
    if (jsFromDb)
        return jobAlertsService.findJobAlertWithCategoriesByJobSeekerId(jsFromDb.jobSeeker.id).then(function (subscription) {
            if (subscription.categories && subscription.categories != 0)
                return redirectUrl;
            else
                return '/subscriptions';
        }, function (err) {
            winston.error('applications.controller findJobAlertWithCategoriesByJobSeekerId : %s', err);
            throw err;
        });
    else
        return redirectUrl;
}, function (err) {
    winston.error('applications.controller findJobSeekerUserByEmail : %s', err);
    throw err;
}).then(function(url) {
    res.redirect(url);
}, function() {
    res.send(500);
});

链接的重要事项是那些return。不可否认,这个解决方案并不是非常令人兴奋,而且与您已有的解决方案相比有很大改进。问题是区分错误条件总是需要嵌套承诺。您可以通过在错误对象中找到相应方法的名称(例如在堆栈跟踪中)来避免这种情况,这样您就可以将错误处理程序组合成通用错误处理程序。

您可以做的第二件事是flatten类别搜索的成功处理程序,但我不确定它是否值得。有了这两个,你的代码现在看起来像这样:

jobSeekerService.findJobSeekerUserByEmail(user.username).then(function (jsFromDb) {
    return jsFromDb
      ? jobAlertsService.findJobAlertWithCategoriesByJobSeekerId(jsFromDb.jobSeeker.id)
      : {categories: 1};
}).then(function (subscription) {
    return (subscription.categories && subscription.categories != 0)
      ? redirectUrl
      : '/subscriptions';
}).then(function(url) {
    res.redirect(url);
}, function(err) {
    winston.error('applications.controller: %s', err);
    res.send(500);
});

这样做的好处是可以捕获subscription null左右的例外情况。