This works fine:
async function onDrop(files: File[]) {
for (let f of files) {
let ref = uploads.push({name: f.name});
(async () => {
await api.uploadFile(f, f.name);
uploads.delete(ref);
})()
}
}
It starts the uploads in parallel and removes each from the uploads list once it is done.
But it has two stylistic issues:
- It has three pairs of parentheses. That’s a lot of parantheses.
- PhpStorm complains Missing await for an async function call because obviously I’m not waiting for the anonymous function to return.
Can I write this better so as to avoid both issues?
I want to use await, not .then().
>Solution :
When performing the map, the function can be async. This avoids an IIFE to trigger the async operation.
async function onDrop(files) {
await Promise.all(files.map(async f => {
let ref = uploads.push({name: f.name});
await api.uploadFile(f, f.name);
uploads.delete(ref);
}));
}
Update: I saw your comment that you want the onDrop function to return without waiting for the files to upload. Therefore, you can do this:
function onDrop(files) {
files.forEach(async f => {
let ref = uploads.push({name: f.name});
await api.uploadFile(f, f.name);
uploads.delete(ref);
});
}