简体   繁体   English

React - 异步等待异步问题

[英]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. 我将文件放在Firebase存储中,我浏览了一个图像列表,并希望将它们逐个放在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". 我希望Map等待最后的“解决”。

You can use an asynchronous for-of loop instead: 您可以使用异步for-of循环:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM