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

Typescript does not recognize that a promise has been fulfilled in my Promise.all

I currently have a setup where I initiate a couple of asynchronous requests and await Promise.all() of them at the end. Typescript however still thinks the promise has not been fulfilled yet.

Example:

const Promise1 = someAsync()
const Promise2 = someAsync()
const Promise3 = someAsync()
await Promise.all([Promise1, Promise2, Promise3])
console.log(Promise1.someData) // is a problem

I suppose I could await for Promise1 again in the console log but that seems a bit patchy, any ideas? or am I wrong about Promise1 being resolved at the console.log point?

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 :

You need to await the resolved values in the return value of Promise.all(). A Promise itself will never have a someData property:

TS Playground

<script type="module">

function someAsync () {
  const result = {someData: Math.random()};
  return Promise.resolve(result);
}

const promise1 = someAsync();
const promise2 = someAsync();
const promise3 = someAsync();
await Promise.all([promise1, promise2, promise3])
console.log(promise1.someData); /* Will log `undefined` because:
                     ~~~~~~~~
Property 'someData' does not exist on type 'Promise<{ someData: number; }>'.(2339) */

// Instead, await the resolved values:
const [resolved1, resolved2, resolved3] = await Promise.all([promise1, promise2, promise3])
console.log(resolved1.someData);
                    //^? (property) someData: number

</script>
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