[英]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.