The only problem with the code you provided is that the result with xmlParser is lost, the forEach loop just iterates, but does not save the results. To save the results, you will need to use Array.map, which will eventually receive Promise, and then Promise.all to wait and get all the results in the array.
I suggest using async / wait from ES2017, which simplifies working with promises. Since the provided code already uses arrow functions, which will require forwarding for compatibility of older browsers, you can add a translation plugin to support ES2017.
In this case, your code will look like this:
function example() { return Promise.all([ array.map(async (value) => { try { const response = await ajaxRequest(value.url); return xmlParser(response); } catch(err) { console.error(err); } }) ]) }
The above code will run all queries in parallel and return results when all queries end. You can also run and process requests one by one, this will also provide access to the previous promise, if that was your question:
async function example(processResult) { for(value of array) { let result; try { // here result has value from previous parsed ajaxRequest. const response = await ajaxRequest(value.url); result = await xmlParser(response); await processResult(result); } catch(err) { console.error(err); } } }
Max Vorobjev
source share