Reputation: 451
When using nested promises, I can't quite figure out what is going wrong in the following implementation. Still trying to learn and fully understand promises.
The code shows the nested promises in their functions. "arrangeAll" waits for the gathering of images from the storage that happens in "auxStorageDownload".
function getCurrentShop (userUID){
const tudo = firestore
.collection('na_publications')
.doc(userUID)
.collection('user_na_publications1')
let array = []
tudo.get().then(snapshot => {
snapshot.forEach(doc => {
array.push(doc.data())
})
}).then(() => {
arrangeAll(array, userUID).then(res => console.log(res))
}
)
}
async function arrangeAll (array, userUID) {
const promises = array.map((elem, i) => {
const result = auxStorageDownload(userUID, elem)
return result
})
await Promise.all(promises).then(promise => {
console.log(promise)
})
}
async function auxStorageDownload (userUID, elem) {
let aux = []
const promises2 = elem.images.map(photoName => { //Fotos de cada publicacao
let result = storage.ref(`publications/${userUID}/${elem.nomeStorage}/${photoName}`).getDownloadURL()
return result
})
await Promise.all(promises2).then(promise => {
console.log(promise)
})
return promises2
}
As you can see in the second image, the promise gathers images regarding 3 publications that have multiple photos (browser console).
But the values received in the "arrangeAll" function are promises, and I would like to use them here to build the final structures for the publications in the website.
Upvotes: 0
Views: 37
Reputation: 4353
This is faulty:
await Promise.all(promises).then(promise => {
console.log(promise)
})
You need to:
then
'd function, you need to return them from that function as well.A direct fix to your code:
return await Promise.all(promises).then(promises => {
// promises is an array of resolved values here
console.log(promises)
return promises;
})
Also in the above code, await
can be dropped, since the returned Promise will be await
ed by the outer calling function anyway (the function calling arrangeAll
.
If you'd like a cleaner solution:
arrangeAll
:async function arrangeAll (array, userUID) {
const promises = array.map((elem, i) => {
const result = auxStorageDownload(userUID, elem)
return result
})
return Promise.all(promises);
}
async function arrangeAll (array, userUID) {
const promises = array.map((elem, i) => {
const result = auxStorageDownload(userUID, elem)
return result
})
const resolved = await Promise.all(promises);
console.log(resolved) /// resolved is an array
return resolved;
}
Upvotes: 1