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

Why does this promise resolve when I am not awaiting it

I have the following promise, but it seems to resolve without me even awaiting it if I run this code in ts playground.

const promises = [later(1000)];


function later(delay:number) {
    return new Promise<void>(function(resolve) {
        setTimeout(() => {
          console.log('test');
          resolve();
        }, delay);
    });
}

I only want it to execute when I call

await Promise.all(promises);

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

>Solution :

As other posts/comments said, later(1000) is evaluated right away and don’t wait for your await Promise.all call to run the promise code.

you could achieve that by doing the following:

const promises = [() => later(1000)];

function later(delay:number) {
    return new Promise<void>(function(resolve) {
        setTimeout(() => {
          console.log('test');
          resolve();
        }, delay);
    });
}

await Promise.all(promises.map(f => f()));
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