0

I am creating an app in ionic+angularfire2 and i want to upload some images to firebase storage, but i want to upload them all at once or at least X at the time (x > 1).

right now i upload them like this

async imageUpload(name, file) {
    // The storage path
    const path = name;
    // The main task
    let img = 'data:image/jpg;base64,' + file;
    return this.task = this.afStorage.ref('/').child(name).putString(img, 'data_url').then((snapshot) => {
    console.log(snapshot)
}).catch((err) => {
    console.log(err);
});

}

then i just loop trought the array that contains the files

let newDocId = this.afStore.createId();
for (var i = 0; i < this.lotProvider.uploadFoto.b64Image.length; i++) {
    let name = 'feriaganadera/'+newDocId +'/'+ (+ new Date()) + "-image_foto_jpeg_" + i + ".jpeg";
    this.imageUpload(name, this.lotProvider.uploadFoto.b64Image[i]);
}

that work, the files are uploaded, but it has to wait for a file to upload the next one.

How can i call the functions asynchronous? so imageUpload does not have to wait for the images.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Carlos Salazar
  • 1,818
  • 5
  • 25
  • 48

1 Answers1

1

Try with Promise.all, first modify your imageUpload function to this to return a promise:

imageUpload(name, file) {

    return new Promise((resolve, reject) =>{
        // The storage path
        const path = name;
        // The main task
        let img = 'data:image/jpg;base64,' + file;
        this.task = this.afStorage.ref('/').child(name).putString(img, 'data_url').then((snapshot) => {
            console.log(snapshot);
            resolve(snapshot);
        }).catch((err) => {
            console.log(err);
            reject(err);
        });
    });
}

And use Promise.all with your array of base64 strings:

Promise.all(this.lotProvider.uploadFoto.b64Image.map(async (img) => {
    console.log(img);
    const content = await this.imageUpload('name','file');
    return content;
}))
.then(values => { 
    console.log(values);
})
.catch((err) => {
    console.log(err);
});

That'll 'launch' your uploads at the time the promises are created, which is as the array is being iterated.

Leonardo G.
  • 177
  • 11