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

Time:08-04

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?

CodePudding user response:

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>

  • Related