cyb*_*bat 7 asynchronous node.js
我有以下示例代码 - 第一部分可以导致异步调用 - 无论哪种方式它应该继续.我不能将其余的代码放在异步回调中,因为它需要在条件为false时运行.那怎么做?
if(condition) {
someAsyncRequest(function(error, result)) {
//do something then continue
}
}
//do this next whether condition is true or not
Run Code Online (Sandbox Code Playgroud)
我假设在函数中放置代码可能是在上面的异步调用中调用该函数的方法,或者在条件为假的情况下在else调用上调用该函数 - 但是有一种替代方法不需要我破坏它在功能上?
我在Node中使用的库经常是Async(https://github.com/caolan/async).最后我检查了这也支持浏览器,所以你应该能够在你的发行版中npm/concat/minify.如果你只在服务器端使用它,你应该考虑https://github.com/continuationlabs/insync,这是一个稍微改进的Async版本,删除了一些浏览器支持.
我在使用条件异步调用时使用的常见模式之一是使用我想按顺序使用的函数填充数组并将其传递给async.waterfall.
我在下面列举了一个例子.
var tasks = [];
if (conditionOne) {
tasks.push(functionOne);
}
if (conditionTwo) {
tasks.push(functionTwo);
}
if (conditionThree) {
tasks.push(functionThree);
}
async.waterfall(tasks, function (err, result) {
// do something with the result.
// if any functions in the task throws an error, this function is
// immediately called with err == <that error>
});
var functionOne = function(callback) {
// do something
// callback(null, some_result);
};
var functionTwo = function(previousResult, callback) {
// do something with previous result if needed
// callback(null, previousResult, some_result);
};
var functionThree = function(previousResult, callback) {
// do something with previous result if needed
// callback(null, some_result);
};
Run Code Online (Sandbox Code Playgroud)
当然你可以使用promises代替.在任何一种情况下,我都希望通过使用async或promises来避免嵌套回调.
你可以通过不使用嵌套回调来避免的一些事情是变量冲突,提升错误,"行进"到右边>>>,>难以读取代码等.
只需声明一些其他函数即可在需要时运行:
var otherFunc = function() {
//do this next whether condition is true or not
}
if(condition) {
someAsyncRequest(function(error, result)) {
//do something then continue
otherFunc();
}
} else {
otherFunc();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4264 次 |
最近记录: |