javascript 类型错误:promise.then(...).then(...).then(...).then(...).catch 不是 Node Js 中的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33677900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: promise.then(...).then(...).then(...).then(...).catch is not a function in Node Js
提问by Vandervidi
Im getting this error and i dont know how to solve it. In a node js server, i'm using some .then() function on a promise and at the end i placed a .catch() function that for some reason is not recognized. I have seen in many places in tutorials that this is how an error is handled. I'm not using any external libraries.
我收到此错误,我不知道如何解决。在节点 js 服务器中,我在 promise 上使用了一些 .then() 函数,最后我放置了一个 .catch() 函数,该函数由于某种原因无法识别。我在教程中的很多地方都看到这是处理错误的方式。我没有使用任何外部库。
The error :
错误 :
TypeError: promise.then(...).then(...).then(...).then(...).catch is not a function
This is my code:
这是我的代码:
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});
});
}
If .catch() is not the correct way to handle promise error, what do you suggest? Im trying to avoid using external libraries and prefer using native javascript
如果 .catch() 不是处理承诺错误的正确方法,你有什么建议?我试图避免使用外部库,而更喜欢使用本机 javascript
EDIT: solution
编辑:解决方案
I added a npm module called blue-bird that helped me solve this.
我添加了一个名为 blue-bird 的 npm 模块,它帮助我解决了这个问题。
回答by dcochran
It looks like you're using Mongoose, which returns its own Promise, not the ES6 promise which includes a catch function. A mongoose Promise has no catch function. You can overwrite the default Promise that Mongoose uses, fortunately:
看起来您正在使用 Mongoose,它返回自己的 Promise,而不是包含 catch 函数的 ES6 承诺。猫鼬 Promise 没有 catch 功能。幸运的是,您可以覆盖 Mongoose 使用的默认 Promise:
http://eddywashere.com/blog/switching-out-callbacks-with-promises-in-mongoose/
http://eddywashere.com/blog/switching-out-callbacks-with-promises-in-mongoose/