Sometimes data isn't being displayed in browser

前端 未结 1 1348
花落未央
花落未央 2021-01-29 07:40

When i click ctr + r sometimes the whole data doesn\'t show up. on my (\"/\") page I have a left side and a right side. The left side should display al

相关标签:
1条回答
  • 2021-01-29 07:55

    The simplest but NOT RECOMMENDED way to do what you want would be the code bellow but it usually leads to callback hell or Pyramid of doom and its hard to read so don't use this!!!!

    Comp.count({}, function(err, count){
       Comp.find({}).remove({}, function(){
          Comp.create(arr, function(err, docs){
             Comp.find({}, ..., function(err, doc){                
                Comp.findOne().skip(random).exec(function(err, result){
                    res.render("index",{})
                })    
             }) 
          })
       })    
    })
    

    another way could be to use async.js

    async.series([
        function(callback){
            Comp.count({}, function(err, count){
                callback(null, count);
            });
        },
        function(callback){
            Comp.find({}).remove({}, function(){
                callback(null);
            });
        },
        function(callback){
            Comp.create(arr, function(err, docs){
                callback(null);
            });
        },
        function(callback){
            Comp.find({}, ..., function(err, doc){ 
                callback(null);
            });
        },
        function(callback){
            Comp.findOne().skip(random).exec(function(err, lastResult){
                callback(null, lastResult);
            });
        }
    ],
    // optional callback, results is an array of results from each callback if any
    function(err, results){
        // results is now equal to [count, lastResult]
        res.render("index",{})
    });
    

    and finally Promises I haven't tried or used this, so not 100% sure but something like this

    var promise = Comp.count({}).exec();
    
    promise.then(function(count) {
        return Comp.find({}).remove({}).exec();
    })
    .then(function() {
        return Comp.create(arr, ).remove({}).exec();
    })
    .then(function() {
        return Comp.find({}).remove({}).exec();
    })
    .then(function() {
        return Comp.find({}).skip(random).exec();
    })
    .then(function(result) {
        res.render("index",{})
    })
    

    Have a look here for some more details about promises on mongoose How to use mongoose Promise - mongo

    0 讨论(0)
提交回复
热议问题