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 abovePero quiero esperar hasta que mi axios termine de buscar, para poder finalmente consolar. registrar mis metadatos reales.
Haz una serie de promesas y luego espéralas con 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));El problema con tu código, que no esperas. El último console.log se ejecuta antes de que el mapa itere todos los elementos.
Deberías usar algo así: https://www.npmjs.com/package/modern-async Por ejemplo
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); }