以同步的方式执行异步调用 [英] Executing asynchronous calls in a synchronous manner
问题描述
我一直在试图总结我的头解决这个问题的最后几个小时,但不能弄明白。我想我还是要习惯的函数式编程风格;)
我写道,通过目录结构和遍历做事某些文件递归函数。该功能使用异步IO的方法。现在,我想执行的时候这整个穿越是做了一些动作。
我将如何确保这一行动已经完成所有解析
来电之后进行,但仍然使用异步IO功能?
变种FS =要求(FS),
PATH =要求('路径');功能解析(DIR){
fs.readdir(DIR,函数(ERR文件){
如果(ERR){
console.error(ERR);
}其他{
// F =文件名,P =路径
VAR每个=功能(F,P){
返回功能(ERR,统计数据){
如果(ERR){
console.error(ERR);
}其他{
如果(stats.isDirectory()){
解析(P);
}否则如果(stats.isFile()){
//做一些东西
}
}
};
}; VAR我;
对于(i = 0; I< files.length;我++){
变种F =文件[I]
VAR P = path.join(DIR,F);
fs.stat(P,每个(F,P));
}
}
});
}解析('。');//做一些东西在这里当异步解析完全汉化
查找步骤模块。它可以异步链函数的调用,并通过从一个结果到另一个。
I've been trying to wrap my head around this issue for the last hours but can't figure it out. I guess I still have to get used to the functional programming style ;)
I wrote a recursive function that traverses through a directory structure and does things to certain files. This functions uses the asynchronous IO methods. Now I want to perform some action when this whole traversing is done.
How would I make sure that this action is performed after all parse
calls have been performed but still use the asynchronous IO functions?
var fs = require('fs'),
path = require('path');
function parse(dir) {
fs.readdir(dir, function (err, files) {
if (err) {
console.error(err);
} else {
// f = filename, p = path
var each = function (f, p) {
return function (err, stats) {
if (err) {
console.error(err);
} else {
if (stats.isDirectory()) {
parse(p);
} else if (stats.isFile()) {
// do some stuff
}
}
};
};
var i;
for (i = 0; i < files.length; i++) {
var f = files[i];
var p = path.join(dir, f);
fs.stat(p, each(f, p));
}
}
});
}
parse('.');
// do some stuff here when async parse completely finished
Look for Step module. It can chain asynchronous functions calls and pass results from one to another.
这篇关于以同步的方式执行异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!