[英]convert asynchronous process in synchronous
I'm playing with javascript and node.js, so I was trying naively to make an asynchronous call synchronous (I know fs lib has readFileSync, this is just for playing) 我正在玩javascript和node.js,所以我试图天真地使异步调用同步(我知道fs lib有readFileSync,这只是为了播放)
So here's the code, it does a loop until the callback changes the flag value, and the loop should break and the flow should continue, but it hangs... 所以这里是代码,它会循环,直到回调更改标志值,循环应该中断并且流程应该继续,但它会挂起......
var fs = require("fs");
//read a file, just something asynchronous
var readfilesync = function(filename){
var getout = false,
result = null,
error = null;
fs.readFile(filename, "utf8", function(err, data){
if (err) {
error = err;
}
else {
result = data;
}
getout = true;
});
while (!getout) {
console.log('---waiting');
}
return (error)? error : result;
};
console.log("========== redis.conf: ",
readfilesync("/var/log/system.log"));
Can anybody help me on a lecture about this ? 有人可以帮我讲一下这个吗? regards.
问候。
while (!getout)
is blocking, so the callback of fs.readFile
never executes and getout
never changes. while (!getout)
挡住,所以回调fs.readFile
从未执行和getout
永远不会改变。
Remember, JS is single threaded. 请记住,JS是单线程的。 The callback can only be executed if resources are available, but they never become available because the
while
loop never terminates. 只有在资源可用时才能执行回调,但它们永远不可用,因为
while
循环永远不会终止。
Maybe this helps to understand the execution model of JavaScript better: MDN - EventLoop . 也许这有助于更好地理解JavaScript的执行模型: MDN - EventLoop 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.