Nodejs Async / Await / Promisse

Asked

Viewed 81 times

0

I have a question, I need to make the code below, wait for the . map to be executed, and parseCategory() calls an API to get the articles. It turns out that the "final..." console output is executed before the . map.

Does anyone have a tip on what would be best practice?

async function parseCategories () {
  var categories = ["business", "entertainment", "health", "sports", "technology"];
  var articles = [];
  await categories.map(category => {
    parseCategory(category).then(result => {
      articles.push(result);
      console.log(category);
    }).catch(error => {
      logger.fail(error);
    });
  });
  await console.log("final...");
}

  • 1

    a possible solution would be to use Promise, and Promise.all to run the precedents in parallel but show the ordered value

2 answers

0

As commented, promisse.all would be an alternative for you to solve this problem. Your code would look like this:

async function parseCategories () {
  var categories = ["business", "entertainment", "health", "sports", "technology"];
  var articles = [];
  await Promise.all(categories.map(category => {
	try {
		result = await parseCategory(category);
		articles.push(result);
	}  catch(error){
		logger.fail(error);
	}
  }));
  await console.log("final...");
}

Here’s another way to solve this problem:

https://flaviocopes.com/javascript-async-await-array-map/

  • Hello Bins, thanks for the answer, the problem that continues is that I need to wait for the return of the parseCategory() method that runs a call to the API... and then push to Articles and then finish...

0

I simulated here the return of its function, and managed to return ordered this way, using Promise.all

async function parseCategories () {
  var categories = ["business", "entertainment", "health", "sports", "technology"];
  var articles = [];

  var result = await categories.map(category => {
            parseCategory(category).then(result => {
              articles.push(result);
              console.log(category);
            }).catch(error => {
              logger.fail(error);
            });
          });


  var con = await console.log("final...");

  Promise.all([result,con])

}
  • Hello Luan, thanks for the answer, the problem that continues is that I need to wait for the return of the parseCategory() method that executes a call to the API... to then push Articles and then finish...

  • and how is your parseCategory? ta as async? I don’t understand the problem, in theory I should run parseCategory first and then run . then

Browser other questions tagged

You are not signed in. Login or sign up in order to post.