我的问题如下:
我在Node中有很多Mysql请求要做,而且它是异步完成的。
在下面的示例中,我希望等待checkExists函数以一种或另一种方式(并填充我的输入变量)在函数doStuffWithInput启动之前完成。除了在各种可能的回调中多次粘贴doStuffWithInput之外(在每个‘input=keys;’之后),我没有任何其他方法.不过,我肯定还有更好的办法。有什么想法吗?
var input;
db.checkExists_weekParents(id,function(count){ //check table existence/number of rows
if(count!==='err'){ //if doesnt exist, create table
db.create_weekParents(id,function(info){
if(info!=='err'){ //as table is empty, create input from a full dataset
db.makeFull_weekParents(id,function(keys){
input = keys;
});
}
});
}else{ //if exists, check number of entries and create input keys as a subset of the full dataset
db.makeDiff_weekParents(id,function(keys){
if(keys.length!==0){
input = keys;
}else{ //if the table already has full dataset, we need to export and start again.
db.export_weekParents(id,function(info){
db.create_weekParents(id,function(info){
if(info!=='err'){
db.makeFull_weekParents(id,function(keys){
input = keys;
});
}
});
});
}
});
}
});一旦所有这些都完成了,我们就有很多事情要做(产生子进程、更多的db操作等等)
doStuffWithInput(input,function(output){
//Tons of stuff here
console.log(output);
})我真的希望这是足够清楚,我会澄清,如果需要。
编辑
尝试用承诺重写似乎是最好的方法,我认为这对像我这样的人来说是一个很好的例子。到目前为止,我已经:
var Q = require('q');
function getInput(){
var dfd = Q.defer();
db.check_weekParents(id,function(count){
console.log('count '+count);
if(count==='err'){
db.create_weekParents(id,function(info){
if(info!=='err'){
console.log('created table');
db.makeDiff_weekParents(id,function(keys){
input = keys;
dfd.resolve(input);
});
}
});
}else{
db.makeDiff_weekParents(id,function(keys){
input=keys;
dfd.resolve(input);
});
}
});
return dfd.promise;
}
getInput().then(function (input) {
console.log(input);
});太神奇了!!
发布于 2013-11-06 19:19:14
您可以使用承诺而不是回调。节点中有许多可能性,而且您正在使用的mysql库甚至可能支持它们。例如,使用Q
function getInput(){
var dfd = Q.defer();
if(count!==='err'){
db.create_weekParents(id,function(info){
/* after everything completes */
dfd.resolve(input);
/* snip */
return dfd.promise;
}那你就可以
getInput().then(function (input) {
doStuffWithInput(input ...
});https://stackoverflow.com/questions/19820565
复制相似问题