Home > other >  Create object inside loop with fetch/await functions
Create object inside loop with fetch/await functions

Time:01-13

I am trying to build a object for my NEXTJS project, where it goes though all the domains, and their pages, then it builds a object with the site name and the page url. This is for my dynamic paging inside the getStaticPaths function.

Now it's not working for me, and i am, in my understanding, doing it the right way. But it seems that i am missing something. I've been googleing for a while now, but nothing really solves and matches the issue i am facing at this point.

I am having the following code right now

Here is the following code i have now

const pages = async () => {
  const allPages = data.map(async ({ params }) => {
    const site = params.site
    const siteInfo = await getSiteInfo(site as string)
    if (typeof siteInfo !== typeof undefined) {
      const siteId = siteInfo[0].site_id
      const allPages = await getPages(site, siteId)
      return allPages.map((pages) => {
        return {
          params: {
            site: params.site,
            slug: pages.page_url,
          },
        }
      })
    }
  })

  return allPages
}

const paths = pages()

console.log(paths)

then the console.log will show me the next output

[ Promise { <pending> }, Promise { <pending> } ]

I've been trying the do things with the catching the respone with pages.then(result) and then logging the result, but that is doing nothing either.

The response i am excepting is something like this for each page.

  params: {
    site: test website,
    slug: 'contact',
  },

CodePudding user response:

I think

const pages = async () => {
  const allPages = await Promise.all(data.map(async ({ params }) => {

should do the trick (await Promise.all to wait for all promises in array to complete and return array with their results)

CodePudding user response:

You can use Promise.all to consume an array of promises, try this:

const result = Promise.all(paths)

CodePudding user response:

The pages function is async, but:

  1. It's not doing anything asynchronous, just returning an array of Promises
  2. You're not awaiting it anyway

You can await the array of Promises within the function:

const allPages = data.map(async ({ params }) => {
  //...
});

return await Promise.all(allPages);

Then await the function when you call it:

const paths = await pages();
console.log(paths);

Or follow it up with a callback:

pages().then(paths => console.log(paths));
  • Related