Async function not waiting long enough to push firestore docs into an array

I am trying to get a bunch (10-1500) of documents from firestore and then once I have them I check the amount I got, and then handle it from there.

I can only get this to work when I have a manual ‘setTimeout’ in between grabbing the docs and checking the array.

The array is not being filled with all of the firestore documents before I check for them but it is in an async function so I am confused to why it isn’t waiting.

  • this is not a firestore issue, I receive all of the documents as I expect.

firestore

javascript async function

async function query(units, days){

  try {

    let allLogs = []

    var ts = moment().subtract(days,'days').valueOf() //ms timestamp from 1 -3 days ago


       await units.forEach(async(e) => {

         let ref = db.collection('units').doc(`${e.unit.superId}`).collection('logs').where('info.ms', '>=', parseInt(ts))

         let docs = await ref.get()  // get all subcollection documents from parent document

          await docs.forEach(async(doc) =>{ // Loop through and push all documents to allLogs array

             allLogs.push(doc.data())

           })
       })


     //If i dont add this: it will always think allLogs is empty. Not waiting long enough for it to be filled

     await new Promise(resolve => setTimeout(resolve, (days+ 1.5) * 1000 )); // x seconds wait for array to be filled


     if (allLogs.length > 0){
       console.log('filled')
     } else {
      console.log('empty')

     }


  } catch(err) {

    console.log(err)
  }


}

975 thoughts on “Async function not waiting long enough to push firestore docs into an array”

  1. Pingback: cialis wikipedia
  2. I absolutely love your website.. Excellent colors &
    theme. Did you develop this site yourself? Please reply back as I’m
    attempting to create my very own blog and would love to
    find out where you got this from or just what the theme is
    called. Thanks!

    Feel free to surf to my web page :: best THC gummies

    Reply
  3. Pingback: what is viagra
  4. Pingback: buy generic viagra
  5. Pingback: viagra price
  6. Pingback: women viagra
  7. Pingback: viagra canada
  8. Pingback: what is amlodipine
  9. Pingback: adcirca vs cialis
  10. Сайт по ссылке https://mtc-sg.kz/teploizolyaciya поможет купить в Алматы качественный материал для тепло- и звукоизоляции помещений. Минеральная плита эластичная и состоит из технических волокон. Из ее положительных качеств можно выделить: хороший воздухообмен, отличную огнестойкость и долговечность. Как правильно выбрать каменную вату (особую форму минваты) рассказано в статье. Доставка осуществляется в любых объемах и в быстрые сроки. Для консультации можно обращаться к менеджеру по телефонам, указанным на сайте.

    Reply
  11. Pingback: xenical 84
  12. Pingback: dapoxetine 1mg
  13. Pingback: finasteride 5mg
  14. Pingback: clomid dosing male
  15. Pretty section of content. I just stumbled upon your site and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I’ll be subscribing to your feeds and even I achievement you access consistently rapidly.

    Reply
  16. Pretty section of content. I just stumbled upon your blog and in accession capital to assert that I get actually enjoyed account your blog posts. Any way I’ll be subscribing to your augment and even I achievement you access consistently rapidly.

    Reply
  17. Pretty section of content. I just stumbled upon your site and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I’ll be subscribing to your feeds and even I achievement you access consistently rapidly.

    Reply
  18. Pretty nice post. I just stumbled upon your weblog and wished to say that I’ve really enjoyed browsing your blog posts. After all I will be subscribing to your rss feed and I hope you write again very soon!

    Reply
  19. Pretty nice post. I just stumbled upon your blog and wanted to say that I have truly enjoyed surfing around your blog posts. After all I’ll be subscribing to your rss feed and I hope you write again soon!

    Reply
  20. Pretty section of content. I just stumbled upon your site and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I’ll be subscribing to your feeds and even I achievement you access consistently rapidly.

    Reply
  21. Pretty great post. I simply stumbled upon your blog and wanted to say that I’ve truly enjoyed surfing around your weblog posts. In any case I’ll be subscribing to your rss feed and I hope you write once more soon!

    Reply
  22. Pretty section of content. I just stumbled upon your site and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I’ll be subscribing to your feeds and even I achievement you access consistently rapidly.

    Reply
  23. Pretty section of content. I just stumbled upon your blog and in accession capital to assert that I get actually enjoyed account your blog posts. Any way I’ll be subscribing to your augment and even I achievement you access consistently rapidly.

    Reply
  24. Pretty nice post. I just stumbled upon your weblog and wished to say that I have truly enjoyed browsing your blog posts. After all I will be subscribing to your feed and I hope you write again very soon!

    Reply
  25. Pretty nice post. I just stumbled upon your weblog and wished to say that I have truly enjoyed browsing your blog posts. After all I will be subscribing to your feed and I hope you write again very soon!

    Reply
  26. Pretty section of content. I just stumbled upon your blog and in accession capital to assert that I get actually enjoyed account your blog posts. Any way I’ll be subscribing to your augment and even I achievement you access consistently rapidly.

    Reply
  27. Pingback: cialis 20mg europe
  28. Специалисты на сайте https://www.thebestwebsite.ru/ предлагают пользователям заказать сайт – адаптивный, визитку, портфолио. Компания может также сделать удобный многостраничный сайт – подробнее обо всех услугах опубликовано на их официальной странице. Можно ознакомиться с ценовой политикой, отзывами и примерами. Больше информации каждый пользователь может получить, проконсультировавшись со специалистами компании, а для заказа можно просто заполнить специальную форму-анкету.

    Reply
  29. Карта мира на странице по ссылке https://map-rus.com/ может быть полезна многим пользователям, в том числе ученикам и студентам. На атласе указана информация о политическом и физическом состоянии континентов, изображения опубликованы в большом разрешении, так что их легко посмотреть с любого устройства. Можно отдельно открыть карту Европы, России, атлас Африки или Австралии, и подробнее ознакомиться с континентом или конкретной страной. Такой сайт станет особенно полезен для тех, кто увлекается географией.

    Reply
  30. Pingback: cialis free sample
  31. Pingback: cialis 10mg sale
  32. Pingback: viagra or cialis
  33. Pingback: viagra australia