React - Async Await Problems with asynchronous

I'm putting files in Firebase Storage, I go through a list of images and want to place them one by one within Firebase. But Map does not expect to finish uploading an image, it starts all the images at the same time and I want it to be one by one.

createProject() {
    let url;
    let prevState = this.state;
    let project = {
        projectName: prevState.projectName,
        description: prevState.description,
        images: [],
    }
    let getUrl = function (url) {
        console.log('DONE' + url);
    }
    prevState.project.images.map(async (image, key) => {
        let url = await this.putFile(image);
        getUrl(url);
    })
}

putFile(file, getUrl) {
    return new Promise(function (resolve, reject) {
        let storageRef = fire.storage().ref('Projects/Images/');
        const image = file;
        const name = file.imageName;
        const metadata = {
            contentType: file.data.type,
        };
        const task = storageRef.child(name).put(image.data, metadata);

        task.on('state_changed', function (snapshot) {
            var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log('Upload is ' + progress + '% done');
            switch (snapshot.state) {
                case firebase.storage.TaskState.PAUSED: // or 'paused'
                    console.log('Upload is paused');
                    break;
                case firebase.storage.TaskState.RUNNING: // or 'running'
                    console.log('Upload is running');
                    break;
            }
        }, function (error) {

        }, function () {
            task.snapshot.ref.getDownloadURL().then(function (downloadURL) {
                resolve(downloadURL);
            });
        });

    });
}

I wanted Map to wait for the last "resolve".

Upvotes: 1

Views: 405

Answers (1)

Tholle
Tholle

Reputation: 112927

You can use an asynchronous for-of loop instead:

async createProject() {
  // ...
  for (let image of prevState.project.images) {
    let url = await this.putFile(image);
    getUrl(url);
  }
}

Upvotes: 3

Related Questions