S3
S3 copied to clipboard
Wrapping in a promise - problem with multiple files being uploaded
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:

What am I doing wrong? All 3 files get uploaded to S3.
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 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.
The above is just JavaScript (ES6 arrow functions are used). The above should work - no dependencies on coffeescript. @msj121
@sscaff1 Ahhh... I am a little behind the times, good to know. I was a little surprised by all the curly braces. Thanks
Thank you, your solution has worked quite well for me.