0

My question is a little similar to this one.

But a little difference is i am calling a async function in loop.

for(var i =0; i < finalArray.length; i++){
  this.getFireStorePayment(code, recentParentId, recentBatchId, mobileNo, 'Processed');
}

It is working fine but in function i am populating an array that is being rendered in DOM.

This:

getFireStorePayment(code, recentParentId, recentBatchId, mobileNo, paymentStatus){
  return new Promise(function (resolve, reject) {
      db.collection('batches').doc(recentParentId).collection('files').doc(recentBatchId).collection('data').where('mobile', '==', mobileNo).limit(1).get().then(function(paymentSnapshot){
          if (paymentSnapshot.size > 0) {
              paymentSnapshot.forEach(paymentDoc => {
                var paymentId = paymentDoc.id;
                if (code !== '0') {
                  var docData = paymentDoc.data();

                  //Following is Array I am populating - partialArray
                  partialArray.push(docData);
                }
              })
          }else{
            console.log("DOC NOT FOUND");
          }
          return resolve();
      })
  }) 
}

Here is DOM render method:

partialArray.map((heading, index) => {
  return(<div className="partial-number" key={index}>
      <img src={heading.profile_picture} width="30px" height="30px" />
      <span className="text-small text-purple text-block-level">{heading.name}</span>
      <span className="text-small text-red text-block-level">{heading.mobile_no}</span>
    </div>)
})

The issue is DOM is being rendered before array is populated. I can't set state to check because there is a loop and it can be of any size.

Where can i setState ?

Noman Ali
  • 3,160
  • 10
  • 43
  • 77
  • 2
    Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Nov 07 '17 at 07:36
  • `My question is a little similar to this one.` not really - your question is more about "how do I work with promises" – Jaromanda X Nov 07 '17 at 07:55
  • `Promise.all(finalArray.map(nothing => this.getFireStorePayment(code, recentParentId, recentBatchId, mobileNo, 'Processed'))).then(results => /* work with results */);` – Jaromanda X Nov 07 '17 at 07:57

0 Answers0