簡體   English   中英

For-await 循環需要時間獲取結果

[英]For-await loop taking time for result

我正在使用 for await 循環遍歷一個數組並匹配 firestore cloud 中的一個值,但不幸的是結果沒有按預期出現; 這是我的代碼

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

當我在模擬器中運行應用程序並且數組包含 2 個項目時,它只是按預期給我結果,但是當數組高於 40 或第 n 個數字時,結果不會按預期更新,幾分鍾后,預期的結果是顯示。 我只想更新 isLoading 狀態 false,當 for await 循環完成其循環並且循環塊內的代碼完成檢查 firebase 時,只有 setIsLoading(false)

對於get()函數,請使用await而不是for await
這應該有效!

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

您可以考慮使用Promise.all ,並等待所有操作完成。

根據之前的建議,最好將其分解為塊並使用 where('value','in', array) 代替。

更新 - 使用 For 循環(我將它們分解為步驟,以便您可以修改以供自己使用)

//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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM