await response of image upload before continue function

后端 未结 1 1908
借酒劲吻你
借酒劲吻你 2021-01-17 03:45

So I am working on a upload function for multiple images in an array. After a lot of struggling I have finally got my upload function to work and the images are showing up i

相关标签:
1条回答
  • 2021-01-17 04:37

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

    Quick sidestep: Handling many promises

    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);
      })
    

    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
      });
    

    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);
            });
    };
    
    0 讨论(0)
提交回复
热议问题