等待节点 js 中函数或回调的 return 值
Wait for return value from function or callback in node js
我正在尝试像这样在节点 js 中设置一些变量:
var perm1 = 0;
var perm2 = 0;
check_tasksAssigned(data,function(resp1) {
perm1 = resp1;
});
check_projectMembers(data,function(resp2) {
perm2 = resp2;
});
if(perm1 && perm2) {
// do some db stuff here
}
但我越来越不确定了。我也这样试过:
var perm1 = check_tasksAssigned(data,function(resp1) {
});
var perm2 = check_projectMembers(data,function(resp1) {
});
if(perm1 && perm2) {
// do some db stuff here
}
也曾这样尝试过,但结果在所有情况下都是一样的:
var perm1 = check_tasksAssigned(data);
var perm2 = check_projectMembers(data);
if(perm1 && perm2) {
// do some db stuff here
}
我该如何解决这个问题?
最好的方法是使用 promises 库。但简短的版本可能看起来像:
var perm1 = 0;
var perm2 = 0;
check_tasksAssigned(data,function(resp1) {
perm1 = resp1;
finish();
});
check_projectMembers(data,function(resp2) {
perm2 = resp2;
finish();
});
function finish() {
if(perm1 && perm2) {
// do some db stuff here
}
}
编辑
根据要求,有承诺,这段代码看起来像:
when.all([
check_tasksAssigned(data)
.then(function(resp1) {
perm1 = resp1;
}),
check_projectMembers(data)
.then(function(resp2) {
perm2 = resp2;
})
])
.then(finish);
但是有很多表达方式,具体取决于具体的 promises 库等
我正在尝试像这样在节点 js 中设置一些变量:
var perm1 = 0;
var perm2 = 0;
check_tasksAssigned(data,function(resp1) {
perm1 = resp1;
});
check_projectMembers(data,function(resp2) {
perm2 = resp2;
});
if(perm1 && perm2) {
// do some db stuff here
}
但我越来越不确定了。我也这样试过:
var perm1 = check_tasksAssigned(data,function(resp1) {
});
var perm2 = check_projectMembers(data,function(resp1) {
});
if(perm1 && perm2) {
// do some db stuff here
}
也曾这样尝试过,但结果在所有情况下都是一样的:
var perm1 = check_tasksAssigned(data);
var perm2 = check_projectMembers(data);
if(perm1 && perm2) {
// do some db stuff here
}
我该如何解决这个问题?
最好的方法是使用 promises 库。但简短的版本可能看起来像:
var perm1 = 0;
var perm2 = 0;
check_tasksAssigned(data,function(resp1) {
perm1 = resp1;
finish();
});
check_projectMembers(data,function(resp2) {
perm2 = resp2;
finish();
});
function finish() {
if(perm1 && perm2) {
// do some db stuff here
}
}
编辑
根据要求,有承诺,这段代码看起来像:
when.all([
check_tasksAssigned(data)
.then(function(resp1) {
perm1 = resp1;
}),
check_projectMembers(data)
.then(function(resp2) {
perm2 = resp2;
})
])
.then(finish);
但是有很多表达方式,具体取决于具体的 promises 库等