简体   繁体   中英

Trying to understand how to use Promise in js

I'm using the native driver for mongoDB. In the db I have about 7 collections and I want create a variable that stores the amount of entries in each collection minus the last collection. Afterwards I want to create another variable that stores the entries of the last collection then I want to pass the variables through the res.render() command and show it on the webpage.

The problem I'm having here is that I'm so used to synchronous execution of functions which in this case goes straight out the window.

The code below is the way I'm thinking, if everything is executed in sync.

var count = 0;
db.listCollections().toArray(function(err,collection){
   for(i = 1; i < collection.length;i++){
      db.collection(collection[i].name).count(function(err,value){
         count = count + value;
      })
   }
   var count2 = db.collection(collection[i].name).count(function(err,value){
         return value;
      })
   res.render('index.html',{data1: count, data2: count2})
})

Obviously this doesn't do want I want to do so I tried playing around with promise, but ended up being even more confused.

You could do something like this with Promises:

Get collection names, iterate over them, and return either count, or entries (if it's the last collection). Then sum up individual counts and send everything to the client.

db.listCollections().toArray()
    .then(collections => {
        let len = collections.length - 1
        return Promise.all(collections.map(({name}, i) => {
          let curr = db.collection(name)
          return i < len ? curr.count() : curr.find().toArray()
        }
        ))
      }
    )
    .then(res => {
      let last = res.pop(),
          count = res.reduce((p, c) => p + c)
      res.render('index.html', {count, last})
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM