What is the best way to wait for the completion of all parallel async functions before returning data?
Request works asynchronously and the following function will return an empty array.
import request from 'request'
// List of urls
const urls = [
'http://someurl.com/1.json',
'http://someurl.com/2.json',
'http://someurl.com/3.json',
]
function getData () {
// An array that will contain data
let result = []
// Request data from all urls
urls.forEach(i => {
// Function works asynchronously
request(i, (err, res, body) => {
if(err) throw err
const data = JSON.parse(body)
result.push(i.someValue)
})
})
return result // Returns an empty array :(
}