我正在使用蓝鸟来传播猫鼬图书馆。因此,我目前发现并保存数据如下:
User.findOneAsync({email: req.body.text})
.then(function(user) {
user.saveAsync()
.spread(function(savedUser){
res.json(savedUser);
})
.catch(function(err) {
res.json({
status: 500,
message: 'foo'
});
});
})
.catch(function(err) {
res.json({
status: 500,
message: 'foo'
});
});
两个catch函数完全相同。这只是一个演示,有时在实际工作中我有两个相同的catch函数。我可以将catch内的函数分成自己的函数。但是,无论如何,我不得不多次编写catch函数。避免重复捕获功能的好方法是什么?任何帮助,将不胜感激。
您实际上可以返回user.saveAsync()
。然后,您的错误将传播到较低的catch函数。像那样:
User.findOneAsync({email: req.body.text})
.then(function(user) {
return user.saveAsync()
.spread(function(savedUser){
res.json(savedUser);
});
})
.catch(function(err) {
res.json({
status: 500,
message: 'foo'
});
});
之所以有效,是因为您spread
返回了Promise。然后,该承诺会沿着外链传递,包括可能的错误。然后,您可以在外链中使用catch
函数来捕获该错误,该函数现在可以捕获内链和外链中的错误,因为它们已连接在一起。
您也可以按照以下方式做一些事情,从而将代码缩短很多,并且没有两个promise链:
User.findOneAsync({email: req.body.text})
.call("saveAsync")
.spread(function (savedUser) {
res.json(savedUser);
})
.catch(function(err) {
res.json({
status: 500,
message: 'foo'
});
});
在兑现承诺时,这通常被视为良好做法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句