且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在继续功能之前等待图像上传的响应

更新时间:2022-02-01 00:15:36

您的大多数uploadImages()代码都是正确的,但是在许多地方,您并未从每个异步操作中返回承诺.

Most of your uploadImages() code was correct, however in many places you didn't return the promise from each asynchronous action.

在处理基于数组的大量异步任务时,建议

When working with lots of asynchronous tasks based on an array, it is advised to map() the array to an array of Promises rather than use a for loop. This allows you to build an array of promises that can be fed to Promise.all() without the need to initialise and push to another array.

let arrayOfPromises = someArray.map((entry) => {
    // do something with 'entry'
    return somePromiseRelatedToEntry();
  });

Promise.all(arrayOfPromises)
  .then((resultsOfPromises) => {
    console.log('All promises resolved successfully');
  })
  .catch((err) => {
    // an error in one of the promises occurred
    console.error(err);
  })

如果任何包含的承诺失败,则以上代码段将失败.要静默忽略单个错误或推迟它们在以后处理,您只需在映射数组步骤内部添加一个catch().

The above snippet will fail if any of the contained promises fail. To silently ignore individual errors or defer them to handle later, you just add a catch() inside the mapped array step.

let arrayOfPromises = someArray.map((entry) => {
    // do something with 'entry'
    return somePromiseRelatedToEntry()
      .catch(err => ({hasError: true, error: err})); // silently ignore errors for processing later
  });

更新的uploadImages()代码

通过这些更改更新代码,将得到以下结果:

Updated uploadImages() code

Updating your code with these changes, gives the following result:

uploadImages = () => {
    const provider = firebase.database().ref(`providers/${uid}`);
    // CHANGED: removed 'let imagesArray = [];', no longer needed

    return Promise.all(photos) // CHANGED: return the promise chain
        .then(photoarray => {
            console.log('all responses are resolved successfully');
            // take each photo, upload it and then return it's download URL
            return Promise.all(photoarray.map((photo) => { // CHANGED: used Promise.all(someArray.map(...)) idiom
              let file = photo.data;
              const path = "Img_" + uuid.v4();
              const storageRef = firebase // CHANGED: renamed 'ref' to 'storageRef'
                    .storage()
                    .ref(`/${uid}/${path}`);
              let metadata = {
                  contentType: 'image/jpeg',
              };

              // upload current photo and get it's download URL
              return storageRef.putString(file, 'base64', metadata) // CHANGED: return the promise chain
                .then(() => {
                  console.log(`${path} was uploaded successfully.`);
                  return storageRef.getDownloadURL() // CHANGED: return the promise chain
                    .then(fileUrl => ({uri: fileUrl}));
                });
            }));
        })
        .then((imagesArray) => {                       // These lines can
          console.log("Out-imgArray: ", imagesArray)   // safely be removed.
          return imagesArray;                          // They are just
        })                                             // for logging.
        .catch((err) => {
          console.error(err);
        });
};