Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nicer way to await something asynchronously

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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);
  });

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading