+ 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?
4 Respuestas
+ 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
+ 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))
}
+ 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()?
+ 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.