I am creating a blogging website, and am writing code that does the following in order:
1. stores multiple photos that the user uploads
2. download their URLs
3. save them to the realtime database.
I wrote the function below to do #1 and #2. Basically the idea is to store all the urls to an array, in this case 'urlarray'.
function url_array_get(){
return new Promise(function(resolve,reject){
let filez=review_photo.files;
let urlarray=[];
let user=firebase.auth().currentUser;
let files=Array.from(filez);
files.forEach(function(file) {
let storageRef=firebase.storage().ref('data/'+user.uid+'/posts/'+file.name);
storageRef.put(file).then(function(snapshot){
snapshot.ref.getDownloadURL().then(function(url) {
urlarray.push(url);
})
})
});
if (!urlarray){
reject("oops");
}
else {
resolve(urlarray);
}
});
}
Here is the part of the upload function code that would upload all the relevant data to the database, including the array of URLs returned by the promise in the function above. (I omitted the rest of the code to make the case concise)
let userpostRef=firebase.database().ref('posts/');
let newpostRef=userpostRef.push();
newpostRef.set({
userid: user.uid,
post_target: rtarget,
post_content:rtext,
time: firebase.database.ServerValue.TIMESTAMP
}).then(function(){
url_array_get().then(function(result){
newpostRef.once('value', function(snapshot) {
newpostRef.update({
postnum:snapshot.key,
photolink:result
})
})})}).
then(function(){
alert("Upload successful!");
window.location.href='/'+username;
})
.catch(function(error){
alert("Error!");
});
}
Here is the issue: The code would write to database everything except the 'photolink', which should be the array of URLs.
Here is what I found out doing debugging:
-Photos are stored without any problem.
-urls are downloaded for each file, and urlarray is returned successfully in the execution code as expected.
What might have gone wrong? I am lost here. Any advice would be very much welcome.
Thanks a lot!