Assume an api server is using HTTP/1.1 and the browser has a limit of 6 concurrent TCP connections per domain.
Does that mean if I do 7 api calls at once with Promise.all
then the last api
will have to wait for the first api
's request to come back over the network?
Promise.all([api(), api(), api(), api(), api(), api(), api()]) // 7 api calls
Also does HTTP/2 solve this problem with multiplexing where all the these API calls will be on the same connection so they don't need to wait for anything?
CodePudding user response:
Yes, but this isn't a limitation particular to Promise.all
. In general, an expression like
anotherFn([fn(), fn(), fn()])
is equivalent to doing
const r1 = fn();
const r2 = fn();
const r3 = fn();
anotherFn([r1, r2, r3]);
Everything inside the argument list gets evaluated before the result is passed. If the process of evaluating everything makes a bunch of API calls, the other function - Promise.all
or anotherFn
cannot possibly do anything about that, because those occur before the function runs.
then the last api will have to wait for the first api's request to come back over the network?
If we can assume that the restrictions are as you've said - the browser is limited to 6 connections to the API at once - then yes.
Yes, HTTP/2 is of great help in these sorts of situations, because they need only one connection per domain, and can send multiple requests over that connection, without running into the browser connection limit.
CodePudding user response:
Does that mean if I do 7 api calls at once with Promise.all then the last api will have to wait for the first api's request to come back over the network?
Yes, it does.
Your Promise.all([api(), api(), ...])
statement will immediately run all api()
function calls. That will cause the first 6 requests to get sent and the 7th will be queued until one of the first 6 finishes in which case the browser will the send the 7th.
This behavior doesn't actually have anything to do with Promise.all()
. The same behavior would occur if you just did this:
const promises = [api(), api(), api(), api(), api(), api(), api()];
Even with just that statement, the 7th http request wouldn't get sent to the host until one of the first 6 had completed. It's entirely because of the browser's connection limits to the same host.
FYI, the Promise.all()
will still work and all the api requests will still work, it will just have to wait a bit longer for all requests to complete than if you weren't hitting the connection limits.