I'm new to node.js and have a non-asynchronous background, thus this makes me feel stupid trying to understand how to properly implement trivial sync tasks asynchronously.
For example, I have an object. I fetch it like this:
objManager.getObject(objId, function(error, object) {
...
})
objManager.getObject implements async call to mongoDB, fetches the object and passes it to the callback as second parameter. Then I need to return a new object, based on the previous one. But there is a flag in an object, which I need to either fetch from DB, or set a default value on. Here's logic I need:
objManager.getObject(objId, function(error, object) {
var objToReturn = {
first_prop: 1,
second_prop: "2",
third_prop: null
};
if (Globals.setThirdDefault) {
// here i need to set it as default.
objToReturn.third_prop = defaultThird;
// Then there is a lot of lines of code
res.send();
} else {
// here I need to fetch the flag from mongoDB,
// and I need to repeat a "lot of lines" in the callback
// as it is async, and if I won't do that, my res.send()
// will be called before callback returns
objManager.getThirdValue(function (error, thirdValue) {
objToReturn.third_prop = thirdValue;
// again, there is a lot of lines of code
res.send();
})
}
})
One way I see it could be managed is by using function for repeated code, but is this correct ? Should I create a lot of functions in order to manage several flags i need to fetch from db, like this ?
objManager.getObject(objId, function(error, object) {
var objToReturn = {
first_prop: 1,
second_prop: "2",
third_prop: null
};
var manageThird = function(thirdProp) {
objToReturn.third_prop = thirdProp;
// here will be my lines of code
}
if (Globals.setThirdDefault) {
manageThird(defaultThird);
res.send();
} else {
objManager.getThirdValue(function (error, thirdValue) {
manageThird(thirdValue);
res.send();
})
}
})
Will this work anyway ?