tl;dr Need some help with Promises.
Here's a little scraper function at the core of it all:
function request(method, url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = resolve;
xhr.onerror = reject;
xhr.send();
});
}
I also have a fairly large list of profiles I'd like to resolve:
const profiles = ['http://www.somesite.com/profile/1',
'http://www.somesite.com/profile/2'] // 100+ more
How do I process them in batches of, say, 5 at a time?
Here's my thought process so far:
- Split into chunks of N using _.chunk()
- Await Promise.all() resolving said chunk
Here's what I have so far:
async function processProfileBatch(batchOfUrls) {
let promises = [];
// Populate promises
for (let i = 0; i < batchOfUrls.length; i++) {
let url = batchOfUrls[i]
promises.push(request('GET', url))
}
// Wait for .all to resolve
return await Promise.all(promises)
}
const profileBatches = _.chunk(profileLinks, 3)
for (let i = 0; i < profileBatches.length; i++) {
let processedBatch = await processProfileBatch(profileBatches[i])
console.log(new Date(), 'processedBatch', processedBatch);
}
Unfortunately this just returns ProgressEvent
s; upon inspection the xhr contained within has .responseText
set to "" even though readyState
is 4: