【发布时间】:2016-02-14 03:48:18
【问题描述】:
我收到此错误,我不知道如何解决它。 在节点 js 服务器中,我在 promise 上使用了一些 .then() 函数,最后我放置了一个 .catch() 函数,由于某种原因无法识别。 我在教程的很多地方都看到这是处理错误的方式。 我没有使用任何外部库。
错误:
TypeError: promise.then(...).then(...).then(...).then(...).catch is not a function
这是我的代码:
exports.joinAlbum = function(req, res){
var promise = Album.findOne().where({'shortId': req.body.shortId}).exec(); // Returns a promise
promise.then(function(albumDoc){
console.log('Then #1');
.....
}
return albumDoc.save(); // Returns a promise
})
.then(function(albumDoc){
console.log('Then #2');
.....
return User.findById(req.body.userId).exec(); // Returns a promise
})
.then(function(userDoc){
console.log('Then #3');
........
return userDoc.save(); // Returns a promise
})
// Return a response
.then(function(savedUserDoc){
console.log('Then #4');
return res.status(200).json({success: true});
})
//Error handler
.catch(function(err){
console.log('Catch #1');
console.log(err);
res.status(200).json({success: false});
});
}
如果 .catch() 不是处理承诺错误的正确方法,你有什么建议?我试图避免使用外部库并更喜欢使用本机 javascript
编辑:解决方案
我添加了一个名为 blue-bird 的 npm 模块来帮助我解决这个问题。
【问题讨论】:
-
.catch()用于try块。如果在then块中返回错误,则抛出一个新错误 -
如果当前的answer 没有帮助,请说明
Album.findOne().where()返回什么样的Promise,如果不是ES6,在哪个库中。也许还包括您正在使用的 node.js 版本。
标签: javascript node.js promise