Skip to content

Instantly share code, notes, and snippets.

@jrgleason
Last active July 14, 2023 04:47
Show Gist options
  • Save jrgleason/eeed880f430dfc75ccd4330645c9109f to your computer and use it in GitHub Desktop.
Save jrgleason/eeed880f430dfc75ccd4330645c9109f to your computer and use it in GitHub Desktop.
StackOverflowHelp Promises
const axios = require("axios");
class Test {
view1: { id: number, name: string } | undefined;
view2: { id: number, name: string } | undefined;
view3: { id: number, name: string } | undefined;
extra_photos: { id: number, name: string }[] | undefined
async downloadFile(id: number, name: string): Promise<File> {
const response = await axios({
url: `/file/${id}`,
method: "GET",
responseType: "blob",
})
return new File([response.data], name);
}
async downloadFiles() {
let extraPhotos;
let fileView1;
let fileView2;
let fileView3;
if(this.extra_photos != null){
const files = this.extra_photos.map(async (photo) => {
//Promise<void>
})
const collection = [
this.view1 ? this.downloadFile(this.view1.id, this.view1?.name) : Promise.resolve(null),
this.view2 ? this.downloadFile(this.view2.id, this.view2?.name) : Promise.resolve(null),
this.view3 ? this.downloadFile(this.view3.id, this.view3?.name) : Promise.resolve(null)
]
collection.concat(this.extra_photos.map((photo)=>this.downloadFile(photo.id, photo.name)));
const res = await Promise.all(collection);
let [fileView1, fileView2, fileView3] = res; //File | undefined
let filesExtraPhotos = await Promise.all(
this.extra_photos.map(
(photo)=>this.downloadFile(photo.id, photo.name)
)
); //File[]
}
return {
fileView1,
fileView2,
fileView3,
extraPhotos
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment