I've been learning about Promises in JS and although its been pretty exciting its also been a bit frustrating. So I'm working on some code that will allow users to drag-and-drop Files and Folders to my web app. However some processes are dependent on others to complete.
My idea is to capture all fileItems (for additional context they're of type FileSystemEntry), then convert them to an object type 'File Upload Object' (my own custom class), then push them all into an array of the same type, to then finally display them on the screen.
Here is my attempt to the solution:
First I want to create a new instance of an object so I can push it into the array.
async returnFileUploadObject(file): Promise<FileUploadObject> {
let fileModTime;
let fileSize;
return new Promise((resolve, reject) => {
try {
file.getMetadata((metadata) => {
fileModTime = metadata.modificationTime;
fileSize = metadata.size;
const fileUploadObj = new FileUploadObject(file.name, fileModTime, fileSize, String(this.uploadState.Spinner), false, file.fullPath);
resolve (fileUploadObj);
});
} catch (e) {
fileModTime = Date.now();
fileSize = 0;
const fileUploadObj = new FileUploadObject(file.name, fileModTime, fileSize, String(this.uploadState.Spinner), false, file.fullPath);
resolve(fileUploadObj);
}
});
}
Then, I want to push that new object into an array.
async createFileObjectList(fileEntries): Promise<FileUploadObject[]> {
return new Promise(async (resolve, reject) => {
let list = [];
for (let file of fileEntries) {
let fileObj = await this.returnFileUploadObject(file);
list.push(fileObj);
}
console.log('Time to resolve this promise', list);
resolve(list);
});
}
Once the array is finished being built, I want to pass it back to another list that will then display the files in HTML:
async dropFiles(items) {
// createFileObjectList
this.fileUploadList = await this.createFileObjectList(items);
console.log('File Upload List', this.fileUploadList);
}
I thought I was doing everything correctly with Promises but when I console.log the results, the arrays appear to have items (28 FileUploadObjs) but actually have a length of 0. I also want to note that sometimes the console.log statement "console.log('Time to resolve this promise', list);" does print out the items in the array - sometimes.
Any kind of help would be greatly appreciated! I am really trying my best to understand Promises and I want my code to finally work. Also any tips for better coding practices when using Promises would be awesome too, thanks! If you need more clarification, I'd be happy to provide it to you.