如何以非阻塞方式在 Node.js 中搜索数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11286979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:57:06  来源:igfitidea点击:

How to search in an array in Node.js in a non-blocking way?

node.js

提问by piggyback

I have an array which is:

我有一个数组,它是:

[ 4ff023908ed2842c1265d9e4, 4ff0d75c8ed2842c1266099b ]

And I have to find if the following, is inside that array

我必须找到以下内容是否在该数组中

4ff0d75c8ed2842c1266099b

Here is what I wrote:

这是我写的:

Array.prototype.contains = function(k) {
  for(p in this)
     if(this[p] === k)
        return true;
  return false;
}

Apparently, it doesn't work properly, or better sometimes it works, but it looks to me blocking. Is there anyone that can check that one?

显然,它不能正常工作,或者有时它工作得更好,但在我看来它是阻塞的。有没有人可以检查一下?

many thanks

非常感谢

回答by penartur

Non-blocking search function

非阻塞搜索功能

Array.prototype.contains = function(k, callback) {
    var self = this;
    return (function check(i) {
        if (i >= self.length) {
            return callback(false);
        }

        if (self[i] === k) {
            return callback(true);
        }

        return process.nextTick(check.bind(null, i+1));
    }(0));
}

Usage:

用法:

[1, 2, 3, 4, 5].contains(3, function(found) {
    if (found) {
        console.log("Found");
    } else {
        console.log("Not found");
    }
});

However, for searching the value in the array it is better to use Javascript built-in array search function, as it will be much faster (so that you probably won't need it to be non-blocking):

但是,为了搜索数组中的值,最好使用 Javascript 内置的数组搜索功能,因为它会快得多(因此您可能不需要它是非阻塞的):

if ([1, 2, 3, 4, 5].indexOf(3) >= 0) {
    console.log("Found");
} else {
    console.log("Not found");
}

Also, consider the underscorelibrary which makes all the stuff cross-platform: http://underscorejs.org/

另外,请考虑underscore使所有内容跨平台的库:http: //underscorejs.org/