Ad

Promise Not Executing Sequentially

- 1 answer

I'm using a package from npm to scrape metadata from a url called url metadata what i'm trying to do is to loop through a json link list and scrape metadata from each link

code

    doc.edited_feed.items.forEach(item => {
        // get metadata of each item link 
        urlMetadata(item.link).then(metadata => {
        // add new item to the feed with the scraped metadata.image
      console.log("running urlmetadata function")
        feed1.addItem({
          title: item.title,
          link: url,
          description: item.contentSnippet,
          content: item.content,
          id: item.link,
          date: new Date(item.isoDate),
          image: metadata.image
        });
        });


      }
    }); // End Foreach


    console.log("after foreach block");
    response.type("application/xml");
    response.send(feed1.rss2());

The problem is that the metadataurl function is running after sending the response

output

    After foreach block
running urlmetadata function
running urlmetadata function
running urlmetadata function

which is the exact opposite of what i wrote i guess that it s something to do with async function or promise

Any help please :/ ?

Ad

Answer

Create an async function and await each response in a for loop

const funcName = async (items) => {
    for (let i = 0; i < items.length; i++) {
        let metadata = await urlMetadata(item.link);
        // do stuff with metadata
    }
}
Ad
source: stackoverflow.com
Ad