How to write this in asynchronous way? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to write this in asynchronous way?

I have the following code: getElements(elementsArray) { return elementsArray.map({name, attributes} => getElement(name, attributes)); }; elementsArray is an array composed of objects, and these objects (elements) contain name and attributes. The question is, how should I rewrite this method, in order to run this asynchronously? In other words, how to call getElement function on every item of an elementsArray in parallel?

12th Jul 2020, 8:32 PM
Matúš Jurko
Matúš Jurko - avatar
4 Answers
+ 2
Check out this demo code, immediately return from map method of async callback, would get array of promises (in console.log, are {},{},{} empty objects). Use Promise.all .then method would get all the async outputs. https://code.sololearn.com/WtBsLnnAp435/?ref=app
13th Jul 2020, 2:40 PM
Calviղ
Calviղ - avatar
+ 1
The best way to write code in asynchronous way is to use async/await, i'm going to suppose that getElement function is a promise, you just need to make asynchronous the getElements function and do await on each getElement function async getElements(elements Array) { return elementsArray.map(({name,atributtes})=> await getElement(name, attributes)) }
12th Jul 2020, 9:05 PM
Erick Ventura
Erick Ventura - avatar
+ 1
Well, getElement is a sync function. Basically all it does, it generates a regex for the given element and then try to find it with match() in the html document passed as a string. I know that I should be using some kind of parser for that, like JSDOM, but it's a big overkill for this small app... Thank u for the quick response, I will try it, but there's one more thing. What if i used promise.all()?
12th Jul 2020, 9:19 PM
Matúš Jurko
Matúš Jurko - avatar
+ 1
Map method with await callback would return array of promises immediately (synchronously), so it is better to add await promise.all for all the return promises.
13th Jul 2020, 1:48 PM
Calviղ
Calviղ - avatar