解决以下控制流程的最佳方法是什么:
我只想在getSomeOtherData
等于某个值时调用someData
/通过一些条件测试
在这两种情况下,我总是想致电getMoreData
http.createServer(function (req, res) {
getSomeData(client, function(someData) {
// Only call getSomeOtherData if someData passes some conditional test
getSomeOtherData(client, function(someOtherData) {
// Always call getMoreData
getMoreData(client, function(moreData) {
res.end();
});
});
});
});
答案 0 :(得分:3)
没有很好的解决方案;我发现最好的是创建一个本地函数来处理剩下的常见工作:
http.createServer(function (req, res) {
getSomeData(client, function(someData) {
function getMoreAndEnd() {
getMoreData(client, function(moreData) {
res.end();
});
}
if (someData) {
getSomeOtherData(client, function(someOtherData) {
getMoreAndEnd();
});
} else {
getMoreAndEnd();
}
});
});
答案 1 :(得分:2)
这是你想要的吗?
http.createServer(function (req, res) {
getSomeData(client, function(someData) {
function myFunction (callback) {
// Only call getSomeOtherData if someData passes some conditional test
if (someData) {
getSomeOtherData(client, function(someOtherData) {
// Do something.
});
}
callback();
}
myFunction(function () {
// Always call getMoreData
getMoreData(client, function(moreData) {
res.end();
});
});
});
});