S3 icon indicating copy to clipboard operation
S3 copied to clipboard

Wrapping in a promise - problem with multiple files being uploaded

Open sscaff1 opened this issue 8 years ago • 5 comments

export const uploadFile = (file, path, singleFile = true, encoding = false) =>
  new Promise((resolve, reject) => {
    if (!file || !path) {
      reject('no file');
    }
    const uploadParams = {
      [singleFile ? 'file' : 'files']: file,
      path,
    };
    if (encoding) {
      uploadParams.encoding = 'base64';
    }
    S3.upload(uploadParams, (error, uploadedFile) => {
      if (error) {
        reject(error);
      }
      resolve(uploadedFile);
    });
  });

Above is my promise for uploading files. The files upload fine. The problem that I'm having is that when the promise resolves with multiple files I only get 1 file (the last file back). How do I get the array of paths back?

My file list looks like this:

screen shot 2016-11-11 at 2 32 29 pm

What am I doing wrong? All 3 files get uploaded to S3.

sscaff1 avatar Nov 11 '16 22:11 sscaff1

const uploadPromise = (params) => (
  new Promise((resolve, reject) => {
    S3.upload(params, (error, uploadedFile) => {
      if (error) {
        reject(error);
      }
      resolve(uploadedFile);
    });
  })
);

export const uploadFile = (file, path, singleFile = true, encoding = false) => {
  const uploadParams = {
    file,
    path,
  };
  if (!file || !path) {
    throw new Error('no file');
  }
  if (encoding) {
    uploadParams.encoding = 'base64';
  }
  if (singleFile) {
    return uploadPromise(uploadParams);
  }
  const returnedObjects = [];
  const promises = [];
  for (let i = 0; i < file.length; i++) {
    const newParams = {
      file: file[i],
      path,
    };
    promises.push(
      uploadPromise(newParams)
      .then(upload => (returnedObjects.push(upload)))
    );
  }
  return Promise.all(promises)
  .then(() => returnedObjects)
  .catch(error => console.log(error));
};

That works incase anyone is trying to do the same.

sscaff1 avatar Nov 11 '16 23:11 sscaff1

@sscaff1 I am trying to do the same, ran into the same exact issue actually. However, I am not versed at all in coffeescript. Is there a simplified Javascript piece of code? A little new at promises as well.

Thanks for the above though.

msj121 avatar Dec 20 '16 00:12 msj121

The above is just JavaScript (ES6 arrow functions are used). The above should work - no dependencies on coffeescript. @msj121

sscaff1 avatar Dec 20 '16 16:12 sscaff1

@sscaff1 Ahhh... I am a little behind the times, good to know. I was a little surprised by all the curly braces. Thanks

msj121 avatar Dec 21 '16 19:12 msj121

Thank you, your solution has worked quite well for me.

msj121 avatar Feb 09 '17 06:02 msj121