简体   繁体   English

链接这些嵌套承诺的正确方法是什么?

[英]What is the right way to chain these nested promises?

I'm doing multiple database queries in my app.我在我的应用程序中执行多个数据库查询。 First is:首先是:

var promise1 = fetchDataWithLatParam()
var promise2 = fetchDataWithLngParam()

return Promise.all([promise1, promise2]).then((results) => {
          var items1 = results[0].data()
          var items2 = results[1].data()

          var intersection = items1.filter(a => items2.some(b => a.name === b.name))
          res.send(intersection)
          return intersection
})

This was working good enough until I introduced a reference-type into the database.在我将引用类型引入数据库之前,这已经足够好用了。 So now in the then I need to do an extra in the intersection query which I did by introducing a map() into the chain with item.user = item.user.get() .所以现在我需要在交集查询中做一个额外的事情,我通过使用item.user = item.user.get()将 map() 引入到链中。 But that failed since it stored the unresolved promise instead, so I wrote a workaround like:但这失败了,因为它存储了未解析的 promise,所以我写了一个解决方法,例如:

  var referentialPromises = []
  var intersection = items1
                        .filter(a => items2.some(b => a.name === b.name))
                        .map(item => {
                            referentialPromises.push(item.user.get().then((result) => {
                                 item.user = result.data()
                            })
                        })

  Promise.all(referentialPromises).then(() => {
      res.send(intersection)
      return intersection
  })

Which works if I turn off the lint checks that gives a warning ie nested promises shouldn't exist.如果我关闭给出警告的 lint 检查,即不应该存在嵌套的承诺,这会起作用。 Now I'm curious as to how to fix this issue coz I cannot push into my production server as it has fixed linting rules that cannot be broken.现在我很好奇如何解决这个问题,因为我无法推送到我的生产服务器,因为它具有无法破坏的固定 linting 规则。

I am not sure about the linting, but you can simplify a bit your code like this:我不确定 linting,但您可以像这样简化代码:

var allThePromises =
  items1
     .filter(a => items2.some(b => a.name === b.name))
     .map(item => item.user.get().then((result) => result.data()));

Promise.all(allThePromises).then((results) => {
 // ... do something with the results
})

Why don't you try async/await ?你为什么不尝试async/await It can help you avoid these Promise-hell problems.它可以帮助您避免这些 Promise-hell 问题。

var promise1 = fetchDataWithLatParam()
var promise2 = fetchDataWithLngParam()

var results = await Promise.all([promise1, promise2])
var items1 = results[0].data()
var items2 = results[1].data()

var referentialPromises = items1
    .filter(a => items2.some(b => a.name === b.name))
    .map(item => {
        return item.user.get().then((result) => {
            item.user = result.data()
        })
    }) 

var intersection = await Promise.all(referentialPromises)
res.send(intersection)

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

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