我是node.js的新手并且具有非异步背景,因此这让我感到愚蠢,试图理解如何异步地正确实现简单的同步任务。
例如,我有一个对象。我这样拿它:
objManager.getObject(objId, function(error, object) {
...
})
objManager.getObject实现对mongoDB的异步调用,获取对象并将其作为第二个参数传递给回调。然后我需要返回一个基于前一个对象的新对象。但是在对象中有一个标志,我需要从DB中获取,或者设置默认值。这是我需要的逻辑:
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();
})
}
})
我认为可以管理的一种方法是使用重复代码的函数,但这是正确的吗?我应该创建很多函数来管理我需要从db中获取的几个标志,像这样吗?
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();
})
}
})
无论如何这会起作用吗?