草庐IT

JavaScript 代码未按所需顺序运行(Node.js、MongoDB)

coder 2023-11-04 原文

我知道 Node.js 的非阻塞 I/O 以及什么是异步函数,但我很难指出为什么这段代码会像它运行时那样运行。

我正在连接到 MongoDB 集合,搜索重复项,将第一个重复的值放在数组对象 (dupIndex) 中。 当数组打印时我看到 2 个值 (console.log(dupIndex);),但当我稍后使用 .length 属性时看到 0 个值 (console.log(dupIndex.length);) -- 当我实际期待 2.

我想用我在 dupIndex 中的数据继续操作集合(比如使用 deleteMany 方法),但是如果它显示 0,我不能,至少不能这样。有人可以解释一下并帮助我解决这个问题吗?

谢谢!

//connect us to a running MongoDB server
const {MongoClient, ObjectID} = require('mongodb');

var dataBase = "TodoApp";
//connecting to a database
//connects to the database /TodoApp, if no such db exists it auto creates it
MongoClient.connect(`mongodb://localhost:27017/${dataBase}`, (err, db)=>{
    if(err){
        //return or 'else' - so if an error happens, it won't continue
        return console.log(`Unable to connect. Error: ${err}`);
    }

    console.log(`Connected to MongoDB server. Database: ${dataBase}.`);
        var dupIndex = [];
    //find all
    db.collection('Todos')
    .find()
    .toArray().then((docs) => {
        for ( var i =0; i< docs.length -1; i++){
            for(var j =i+1; j< docs.length; j++){
                    if(docs[i].text === docs[j].text)
                    {   
                        console.log(`in`);
                        dupIndex.push(docs[i].text);
                        i++;
                    }
            }
        }
        console.log(dupIndex);

    }, (err)=> {
        console.log(`unable t o fetch`);
    });

    console.log(dupIndex.length);
    // for(var i = 0; dupIndex)
    //close the connection to the db
    db.close();
});

最佳答案

因为console.log(dupIndex.length);在嵌套循环之前运行。

db.collection('Todos')
.find()
.toArray()

这是一个异步调用,控制被传递给 console.log(dupIndex.length); 尝试写 console.log(dupIndex.length);在 console.log(dupIndex) 旁边;

例如:

 db.collection('Todos')
.find()
.toArray().then((docs) => {
    for ( var i =0; i< docs.length -1; i++){
        for(var j =i+1; j< docs.length; j++){
                if(docs[i].text === docs[j].text)
                {   
                    dupIndex.push(docs[i].text);
                    i++;
                }
        }
    }
    return dupIndex;
}, (dupIndexRecieved)=> {
    console.log(dupIndexRecieved.length); data recieved here
}, (err)=> {
    console.log(`unable t o fetch`);
});

关于JavaScript 代码未按所需顺序运行(Node.js、MongoDB),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41661459/

有关JavaScript 代码未按所需顺序运行(Node.js、MongoDB)的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  3. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  4. ruby - 如何每月在 Heroku 运行一次 Scheduler 插件? - 2

    在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/

  5. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  6. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  7. ruby - Chef 执行非顺序配方 - 2

    我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul

  8. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  9. ruby-on-rails - 浏览 Ruby 源代码 - 2

    我的主要目标是能够完全理解我正在使用的库/gem。我尝试在Github上从头到尾阅读源代码,但这真的很难。我认为更有趣、更温和的踏脚石就是在使用时阅读每个库/gem方法的源代码。例如,我想知道RubyonRails中的redirect_to方法是如何工作的:如何查找redirect_to方法的源代码?我知道在pry中我可以执行类似show-methodmethod的操作,但我如何才能对Rails框架中的方法执行此操作?您对我如何更好地理解Gem及其API有什么建议吗?仅仅阅读源代码似乎真的很难,尤其是对于框架。谢谢! 最佳答案 Ru

  10. ruby - 模块嵌套代码风格偏好 - 2

    我的假设是moduleAmoduleBendend和moduleA::Bend是一样的。我能够从thisblog找到解决方案,thisSOthread和andthisSOthread.为什么以及什么时候应该更喜欢紧凑语法A::B而不是另一个,因为它显然有一个缺点?我有一种直觉,它可能与性能有关,因为在更多命名空间中查找常量需要更多计算。但是我无法通过对普通类进行基准测试来验证这一点。 最佳答案 这两种写作方法经常被混淆。首先要说的是,据我所知,没有可衡量的性能差异。(在下面的书面示例中不断查找)最明显的区别,可能也是最著名的,是你的

随机推荐