简体   繁体   中英

For-await loop taking time for result

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)

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);
}();
(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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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