Node.js猫鼬-如何避免回调地狱? [英] Nodejs Mongoose - how to avoid callback hell?
本文介绍了Node.js猫鼬-如何避免回调地狱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Mongoose一段时间后,我可能做错了.当您有太多回调时,我发现很难阅读,例如:
I might be doing it wrong with Mongoose after using it for a while. I find it difficult to read when you have too much callbacks, eg:
我想找到一个文档并进行更新.我需要先找到它,然后update
将位于findOne
的回调中.
I want to find a document and update it. I need to find it first, then the update
will be inside the callback of the findOne
.
var sam = new Character({ name: 'Sam', inventory: {}});
Character.findOne({ name: 'Sam' }, function(err, character) {
console.log(character);
// now I want to update it.
character.update({... }, function(err, characterID) {
// now I want to know the size of the document after the update.
Character.findOne({ _id: characterID }, function(err, character) {
// Now update it again....
});
});
});
它最终以意大利面代码结尾!
It ends up a spaghetti code eventually!
你明白我的意思吗?
有什么想法可以做得更好吗?
Any ideas how to do it better?
在没有所有这些回调的情况下,mongodb native会更好吗?
Or mongodb native is better without all these callbacks?
Character.findOne({...}, function(err, character) {
return character.update(...);
}).select("-field1 -field2").then(function(data) {
//
}).catch(function(error) {
// Handle any error from all above steps
}).done();
错误:
TypeError: Character.findOne(...).select(...).then(...).catch(...).done is not a function
推荐答案
您可以在nodejs中使用 q promise的链接
You can use chaining of q promise in nodejs
var Q = require('q');
function findOne(filter) {
return Q.Promise(function(resolve, reject) {
Character.findOne(filter, function(err, character) {
resolve({
err: err,
character: character
});
});
});
}
function update(data) {
return Q.Promise(function(resolve, reject) {
character.update(data, function(err, characterID) {
resolve({
err: err,
characterID: characterID
});
});
});
}
findOne({ name: 'Sam' }).then(function(data) {
if (!data.err) {
// now you can update it.
return update(data.character);
} else {
throw new Error(data.err);
}
}).then(function(data) {
if (!data.err) {
// now you can update it.
return update(data.characterId);
} else {
throw new Error(data.err);
}
return findOne({ id: characterId });
}).then(function(data) {
if (!data.err) {
// now you can update it.
return update(data.character);
} else {
throw new Error(data.err);
}
}).catch(function(error) {
// Handle any error from all above steps
}).done();
这篇关于Node.js猫鼬-如何避免回调地狱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文