[Sorry for duplicate question]
This is my working JS-function for uploading images. The problem is that the function for uploading the "tool"(data) to the database, don't wait for the imageURL from Firebase. I need some sort of async / await without using a timeout. I want to upload the data to firebase as soon as all of the imageURLs are uploaded.
Here is JS-code (vuex):
createTool ({ commit }, payload) {
let toolData = {
croppas: payload.croppas,
title: payload.title
}
var imageURLS = []
// outputArray = imageURLS
function forEachImage(images, outputArray) {
return new Promise((resolve) => {
images.forEach(file => {
file.generateBlob(
blob => {
if (blob != null) {
let rand = (Math.random().toString(36).substring(2, 16) + Math.random().toString(36).substring(2, 16)).toUpperCase()
let imageRef = firebase.storage().ref('toolImages/').child(rand)
imageRef.put(blob)
.then( data => {
imageRef.getDownloadURL()
.then( downloadURL => {
console.log('The Download Link is: ', downloadURL)
outputArray.push(downloadURL)
console.log('The imageArray after push is: ', outputArray)
})
})
}
})
})
resolve()
})
}
async function uploadEachImage () {
await forEachImage(toolData.croppas, imageURLS)
console.log(imageURLS)
const mergedToolData = {
title: payload.title,
URLS: imageURLS
}
console.log('Uploading to database...')
firebase.database().ref('tools').push(mergedToolData)
.then((data) => {
const key = data.key
commit('createTool', {
title: payload.title,
URLS: imageURLS,
id: key
})
})
}
uploadEachImage()
},
My attempt here is to wait for the function "forEachImage" to complete.
The function will:
- loop through all the images
- generate a blob (image)
- upload the blob to firebase
- Recieve a URL and put it in a "global" variable (imageURLS)
My desired outcome is this: after that function has completeted all the images, the async function continues and upload the data to the database (also containing the imageURLS[]. As I mentioned, I want to do this without using a timeout. (timer).