I am trying to process concurrent AJAX requests with vanilla JavaScript. Below is the sample code I've been working with
function getInfoViaConcurrency(ids) {
let infoPromiseArr = ids.map(id=> { infoPromiseArr.push(getInfoViaAjax(id)); });
return Promise.all(infoPromiseArr).then(values => { return values; });
}
function getInfoViaAjax(id) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', `API URL`);
xhr.onload = function() {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText));
}
else {
reject(xhr.status);
}
};
xhr.send();
})
}
Does using promise.all suffice to promote concurrency? can someone suggest any improvements?
1 Answer 1
Does using promise.all suffice to promote concurrency?
It's not really Promise.all
that does it. You're starting your requests without waiting for the previous ones to complete, so yes, they run concurrently. All Promise.all
does is let you know when all of the promises you give it have resolved (or when the first one rejects).
can someone suggest any improvements?
Some thoughts:
- In
getInfoViaConcurrency
:- Your use of
map
is incorrect, kind of a mash-up of your originalforEach
(from your now-deleted post on SO) andmap
- You can pass
getInfoViaAjax
directly tomap
- The
then
handler on thePromise.all
serves no purpose and can be removed
- Your use of
- In
getInfoViaAjax
, you could usefetch
on modern browsers rather thanXMLHttpRequest
So getInfoViaConcurrency
could be:
function getInfoViaConcurrency(ids) {
return Promise.all(ids.map(getInfoViaAjax));
}
and if you want to use fetch
, getInfoViaAjax
could be:
function getInfoViaAjax(id) {
return fetch({/*...appropriate options and URL...*/}).then(response => {
if (!response.ok) {
throw new Error(/*...whatever you want to say here...*/);
}
return response.text();
});
}
-
1\$\begingroup\$ Thanks a lot for answering this in SO and in here with more details. \$\endgroup\$NiK– NiK2017年12月03日 17:40:15 +00:00Commented Dec 3, 2017 at 17:40
Explore related questions
See similar questions with these tags.