简体   繁体   English

试图了解如何在js中使用Promise

[英]Trying to understand how to use Promise in js

I'm using the native driver for mongoDB. 我正在为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. 在数据库中,我大约有7个集合,我想创建一个变量,该变量存储每个集合中的条目数减去最后一个集合。 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. 之后,我想创建另一个变量,该变量存储最后一个集合的条目,然后我想通过res.render()命令传递这些变量并将其显示在网页上。

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: 您可以使用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})
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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