【问题标题】:How to wait for moongose to finish query?如何等待猫鼬完成查询?
【发布时间】:2016-11-19 22:27:44
【问题描述】:
router.post('/logout', function(req, res) {
    if(req.body.newList){
    var aux= JSON.parse(req.body.newList); 
    var aux1;
    var i=0;
    while(i<aux.length){
        aux1=aux[i];
        Task.findOne({username:aux1.username,text:aux1.text},function(err,res){
            if(res){
                i++;
            }else{
                task= new Task({username:aux1.username,text:aux1.text,state:aux1.state});
                task.save(function(err){
                    i++;
                });
            }
        });
    }
}

嗯,到目前为止我有这个。 aux 存储一组 json 对象,它们没有_id,所以.. 我需要在需要时逐个遍历它们保存。问题是(我认为)异步,因为此代码仅将数组的最后一个元素保存在数据库中 n 次,即 n 应保存的不同元素的数量**(参见示例)。所以,我认为月光查询的异步行为让我很头疼。大概一直迭代等待查询结果,然后用数组的最后一个值保存。

** 例如,如果我有这些值用于保存 [{username:'x',text:'a'},{username:'x',text:'aa'},{username:'x',text:'aaa'}]..

它保存[{username:'x',text:'aaa'},{username:'x',text:'aaa'},{username:'x',text:'aaa'}]

我尝试使用 Promise,但它不起作用.. 可能用错了

【问题讨论】:

    标签: javascript node.js mongodb asynchronous mongoose


    【解决方案1】:

    对于这样的事情,我更喜欢使用caolan's async 库。只需这样做:

    npm install async 添加模块。

    然后将您的代码替换为:

    router.post('/logout', function(req, res) {
        if (req.body.newList) {
            var aux = JSON.parse(req.body.newList);
            var async = require("async");
            async.each(aux, function(aux1, callback) {
    
                Task.findOne({
                    username: aux1.username,
                    text: aux1.text
                }, function(err, res) {
                    if (res) {
                        callback();
                    } else {
                        task = new Task({
                            username: aux1.username,
                            text: aux1.text,
                            state: aux1.state
                        });
                        task.save(function(err) {
                            callback();
                        });
                    }
                });
            }, function(err) {
                // if any of the query processing produced an error, err would equal that error
                if (err) {
                    // One of the iterations produced an error.
                    // All processing will now stop.
                    console.log('A query failed to process');
                } else {
                    console.log('All queries have been processed successfully');
                    //do other things here
                }
            });
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-01-22
      • 2014-03-03
      • 1970-01-01
      • 2016-08-16
      • 2018-08-09
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 2021-03-23
      相关资源
      最近更新 更多