I’m attempting to create a function that will execute simultaneously to send images for Cloud Firestore
. At the moment I’m attempting to simulate a request
with setTimeout
to understand how the function works.
Although I can’t seem to get it to work as expected:
const functionO = async () => {
try {
console.log('before')
const datas = [1,2,3]
await new Promise(async (resolve, reject) => {
await datas.forEach((d) => {
// This is simulating a request to firestore cloud
setTimeout(() => {
console.log(d)
}, 1000)
})
resolve()
})
console.log('after')
} catch (err) {
}
}
The output:
before
after
1
2
3
expected (the numbers can be in different orders, although I need to wait for the promise to finish to continue):
before
1
2
3
after
How I intend to use the function later on:
const functionO = async () => {
try {
console.log('before')
const datas = [1, 2, 3]
await new Promise(async (resolve, reject) => {
images.forEach(async (image) => {
const extension = image?.type?.split('/')[1]
const reference = await storage().ref(
`receitas/${userInfo?.uid}/uid.${extension}`,
)
reference.putFile(file)
})
resolve()
})
console.log('after')
} catch (err) {}
}
The intention is, if something fails on sending a image, it won’t execute the rest of the function.
2
Answers
I believe this is a solution
for…each only accepts synchronous functions, it does not work as expected with asynchronous stuff. You need to use a traditional for-loop or for..of.
I can’t tell you why this is like it is…
Maybe you can find more information in this thread:
Using async/await with a forEach loop