Home > Software engineering >  Await is not as i expected in if else statements
Await is not as i expected in if else statements

Time:04-25

let metadata = [];

    allNFTs.map(async (e) => {
      if (e.metadata) {
        metadata.push(JSON.parse(e.metadata).attributes);
      } else {
        let config = {
          method: "get",
          url: `http://localhost:3000/api/fetch`,
          header: {
            "Content-Type": "application/json",
          },
        };
        const res = await axios(config);
        const attr = res.data.attributes;
        metadata.push(attr);
        console.log(metadata); // this one worked after below
      }
    });

    console.log(metadata); // this one worked before above

enter image description here

But i want to wait till my axios done fetching, so i can finally console.log that my actual metadata.

CodePudding user response:

Make an array of promises, and then await them with Promise.all

const metadataPromises = allNFTs.map((e) => {
  if (e.metadata) {
    return Promise.resolve(JSON.parse(e.metadata).attributes);
  } else {
    let config = {
      method: "get",
      url: `http://localhost:3000/api/fetch`,
      header: {
        "Content-Type": "application/json",
      },
    };
    return axios(config).then((res) => res.data.attributes);
  }
});

// await still has to be in an async function
const metadata = await Promise.all(metadataPromises);

console.log(metadata);

// or use .then
Promise.all(metadataPromises).then((metadata) => console.log(metadata));

CodePudding user response:

The issue with you code, that you don't wait. The latest console.log is execurted before the map iterating all the items.

You should use somehting like that: https://www.npmjs.com/package/modern-async E.g.

async function init() {
   var ma= require('modern-async')
   await ma.mapSeries(allNFTs,async (e)=>{
   if (e.metadata) {
        metadata.push(JSON.parse(e.metadata).attributes);
      } else {
        let config = {
          method: "get",
          url: `http://localhost:3000/api/fetch`,
          header: {
            "Content-Type": "application/json",
          },
        };
        const res = await axios(config);
        const attr = res.data.attributes;
        metadata.push(attr);
        console.log(metadata);
      }
   })
   console.log(metadata);

}
  • Related