Home > Software design >  Promise.all does not resolve promises as expected
Promise.all does not resolve promises as expected

Time:11-07

For some reason this works as expected:

  const metadatasExternal = await Promise.all(
    NFTs.map(n => axios.get(n.metadataOnchain?.data.uri!))
  )

But this doesn't:

  const metadatasExternal = await Promise.all(
    NFTs.map(n => ({
      metadataPDA: n.metadataPDA,
      metadataExternal: axios.get(n.metadataOnchain?.data.uri!),
    }))
  )

Specifically the promises aren't being resolved. This is what I get back:

  {
    metadataPDA: PublicKey {}
    metadataExternal: Promise { <pending> }
  },

Why is that? And how do I fix it? I specifically need to include the metadataPDA key in each promise, otherwise I can't match them to another data structure in the code.

CodePudding user response:

You need to feed Promise.all an array of promises. In your second snippet, you feed it in an array of plain objects, with a promise in one of the keys. Promise.all doesn't know magic, and won't be able to await on the promises you've hidden away within said objects.

Instead, ensure you return promises within the map-

const metadatasExternal = await Promise.all(
    NFTs.map(async n => {
        const data = await axios.get(n.metadataOnchain?.data.uri!);
        return { metadataPDA: n.metadataPDA, metadataExternal: data };
    })
);
  • Related