I use the Q library in nodejs and have not worked too much with promises in the past, but I have semi-complex logic that requires a lot of nesting, and the thought of Q would be a good solution, however I find it seems almost the same as just a callback hell ".
Basically I say 5 methods, all of which require data from the previous or one of the previous. Here is an example:
We start with some binary data that has the sha1 hash file generated from the binary.
var data = {
hash : "XXX"
, binary: ''
}
First we want to see if we have this using this method:
findItemByHash(hash)
If we don’t have it, we need to save it using:
saveItem(hash)
, . , , , :
getItemHierarchy(item_id), item_id, saveItem
"" :
saveUserHierarchy(hierarchy)
, , . , . :
, :
getUserItemByItemId(item_id) - item_id findItemByHash
, .
:
getItemHierarchy(item_id)
saveUserHierarchy(hierarchy)
, , , . . , . , - , .
Q - :
findItemByHash(hash).then(function(res) {
if (!res) {
return saveItem(hash).then(function(item) {
return getItemHierarchy(item.id).then(function(hierarchy) {
return saveUserHierarchy(hierarchy);
});
})
} else {
return getUserItemByItemId(res.id).then(function(user_item) {
if (user_item) {
return user_item;
}
return getItemHierarchy(res.id).then(function(hierarchy) {
return saveUserHierarchy(hierarchy);
});
});
}
})
.fail(function(err) {
console.log(err);
})
.done();
, , . Q?
!