和的NodeJS异步地狱 [英] NodeJS and asynchronous hell

查看:147
本文介绍了和的NodeJS异步地狱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚来到这个可怕的情况我有一个字符串数组每次重新presenting可能存在的文件(例如 var中的文件= ['文件1','文件2','文件3' ] 。我需要遍历这些文件名,并尝试,看看它是否在当前目录存在,如果是的话,停止循环,忘记了剩余的文件的剩余部分。所以基本上我想发现这些的第一个存在的文件,并退回到一个硬codeD消息,如果什么也没有找到。

I just came to this awful situation where I have an array of strings each representing a possibly existing file (e.g. var files = ['file1', 'file2', 'file3']. I need to loop through these file names and try to see if it exists in the current directory, and if it does, stop looping and forget the rest of the remaining files. So basically I want to find the first existing file of those, and fallback to a hard-coded message if nothing was found.

这是我目前有:

var found = false;
files.forEach(function(file) {
  if (found) return false;

  fs.readFileSync(path + file, function(err, data) {
    if (err) return;

    found = true;
    continueWithStuff();
  });
});

if (found === false) {
  // Handle this scenario.
}

这是不好的。它的阻止(readFileSync),因此它的速度慢。

This is bad. It's blocking (readFileSync) thus it's slow.

我不能只供应 fs.readFile 回调方法,它不是那么简单,因为我需要采取的第一个找到的项目......而回调可能所谓在任何随机顺序。我想到一个办法是有,增加一个计数器,并保持的发现/没有找到信息列表和一个回调,当它到达 files.length 计数,然后检查通过发现/没有找到信息,并决定下一步该怎么做。

I can't just supply callback methods for fs.readFile, it's not that simple because I need to take the first found item... and the callbacks may be called at any random order. I think one way would be to have a callback that increases a counter and keeps a list of found/not found information and when it reaches the files.length count, then it checks through the found/not found info and decides what to do next.

这是痛苦的。我看到在事件触发IO性能的伟大,但是这是不能接受的。我有什么选择?

This is painful. I do see the performance greatness in evented IO, but this is unacceptable. What choices do I have?

推荐答案

不要在正常的服务器环境中使用同步的东西 - 事情是单线程的,这将彻底锁定事情在等待该IO的结果绑定环路。 CLI公用=可能正常,服务器=仅好于启动。

Don't use sync stuff in a normal server environment -- things are single threaded and this will completely lock things up while it waits for the results of this io bound loop. CLI utility = probably fine, server = only okay on startup.

异步流控制的公共库是
https://github.com/caolan/async

A common library for asynchronous flow control is https://github.com/caolan/async

async.filter(['file1','file2','file3'], path.exists, function(results){
    // results now equals an array of the existing files
});

如果你想说,避免path.exists的额外要求,那么你可以很容易地pretty编写一个函数第一是做了操作,直到一些测试成功。类似 https://github.com/caolan/async#until - 但你感兴趣的输出

And if you want to say, avoid the extra calls to path.exists, then you could pretty easily write a function 'first' that did the operations until some test succeeded. Similar to https://github.com/caolan/async#until - but you're interested in the output.

这篇关于和的NodeJS异步地狱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆