I'm trying to create a function that gets a presigned s3 url (call 1) and does a put to s3. The only way I'm able to figure it out in my head is using a nested promise which I understand to be an anti-pattern.
Writing it out in js/pseudocode
uploadfile(file){
return new Promise((resolve, reject) => {
axios.get(get-presigned-s3url).then((url) =>{ return axios.put(file)}
})
}
let filePromises = files.forEach(file => uploadfile(file));
promises.all((filePromises) => notifyUpload(filePromises));
I need to return a promise from the uploadfile function to wait for all the promises to resolve. What's the right way to handle this scenario?
Since axios.get
returns a Promise already, you don't need to construct another one around it with new Promise
.
files.forEach
won't work, because forEach
returns undefined
. Use .map
instead, so you have an array of Promises.
const uploadFile = file => axios.get(url)
.then((url) => { return axios.put(file); });
Promise.all(
files.map(uploadFile)
)
.then(notifyUpload)
.catch(handleErrors);