The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

532789 (7) [Avatar] Offline
#1
I need to query multiples firebases collections in order to perform some operations, I've found that my current implementation works for only one single collection but if I try to run a map array over all the collection I need it doesnt work for the the way aws node environment work, I would appreciate any help in how to solve this.

My implementation looks like this:


admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
})
const queryBases = (collection) => {
  return new Promise((resolve, reject) => {
    resolve(admin.firestore()
      .collection(collection)
      .get())
  })
}
module.exports.handler = async (event, context) => {
  context.callbackWaitsForEmptyEventLoop = false
  const response = await queryBases('collection-name-1')
  results.forEach(d => {
    console.log(d.data()) /* it works*/
  })
  return 'exiting'
}



That works like charm, but my use case looks more like this:

module.exports.handler = async (event, context) => {
  context.callbackWaitsForEmptyEventLoop = false
  const results = ['collection-one', 'collection-two']
    .map(async collection => {
      const result = await queryBases(collection)
      result.forEach(ref => {
        console.log(ref.data())
      })
      return result
    })
  return 'exiting'
}


This doesnt work... the lambda stops executing, it doesnt even return from the first call, I know there is a lot of topics and conversation about this kind of async operations into collections but I haven't found a solid solution for this case, any ideas will be appreciated.
Yan Cui (73) [Avatar] Offline
#2
This is a common node.js mistake when it comes to async-await, I've done this myself!

What's happening is that you have mapped the array ['collection-one', 'collection-two'] to an array of Promise, but you have to wait for the promises to complete with Promise.all before you exit from the invocation.

What you need is something like this:

const promises = ['collection-one', 'collection-two']
    .map(async collection => {
      const result = await queryBases(collection)
      result.forEach(ref => {
        console.log(ref.data())
      })
      return result
    })
const results = Promise.all(promises)

// do something with the results

return 'exiting'