For-await loop taking time for result

134 Views Asked by At

I am using for await loop to iterate through an array and match a value inside firestore cloud but unfortunately the result is not coming as expected; here is my code

(async () => {
for await (const element of array) {
firestore().collection('users').where('value', '==', element).get()
.then(async snapshot () => {
setvalue(snapshot.data())
}
setIsLoading(false);
}();

When i run the app in emulator and array contains 2 items, it just give me the result as expected, but when the array is above then 40 or nth number, then the result is not updating as exptected, and after a few minutes, the expected result is display. I just want to update the isLoading state false, when the for await loop finishes its loop and also the code inside the loop block finished checking the firebase then only the setIsLoading(false)

2

There are 2 best solutions below

8
On
(async () => {

const allValues = await Promise.all(array.map( item => {

return firestore().collection('users').where('value', '==', element).get()
.then(async snapshot () => {
 //do something

 return value
}

})

console.log('allValues', allValues)
setIsLoading(false);
}();

You can consider using Promise.all, and wait for all operations to finish.

As per previously advised, better to break it down to chunks and use where('value','in', array) instead.

Update - use For loop (I break them down into steps so you can modify for your own use)

//create a function
const myJob = async() => doSomething

//empty array to hold all the async jobs.
let myPromises = []

//for loop to do whatever u want.
for ( var i = 0; i < 10; i++) {
     myPromises.push(myJob(i));
}

//now call Promise.all with the array of jobs
const myResults = Promise.all(myPromises);
0
On

Instead of for await, use await for your get() function.
This should work!

(async () => {
  for (const element of array) {
    const snapshot = await firestore().collection('users').where('value', '==', element).get();
    setvalue(snapshot.data());
  }
  setIsLoading(false);
}();