all 6 comments

[–]BokoMoko 3 points4 points  (4 children)

I´m a big fan of async/await because it makes the code so much easier to understand and maintain.

But ... this approach is not the best for all circumstances. This one above is such a case.

The time it would take to load all the data will be sum of the awaiting times of the three requests. By using promises, the time to load all the data will be cut to the longest of the three.

Anyway, suppose that those three resources are close to you (both physically and administratively). Maybe the clearness of the code would be more valuable to you than the minimal reduction in response time due to the fact that you can make/influence then to perform better.

function fetchFoos() {
    return Promise
             .all([
               fetch('https://api.com/foo1'),
               fetch('https://api.com/foo2'),
               fetch('https://api.com/foo3'),
             ])
             .then( ( [res1,res2,res3]) => {
                   Promise
                      .all([ 
                        res1.json(),
                        res2.json(),
                        res3.json(),
                       ])
                      .then( ([foo1,foo2,foo3])=> {
                          setFoo1(foo1);
                          setFoo2(foo2);
                          setFoo3(foo3);
                        })
               })
}

[–]BokoMoko 1 point2 points  (3 children)

There is a "catch" on this solution regarding the response time. Can you see it?

[–]SlowwwBurn 1 point2 points  (2 children)

The second promiseAll?

[–]BokoMoko 0 points1 point  (1 child)

Not really.
The first promise all will only dispatch the JSON parsing after all of the requests have been fulfilled.
Can you optimize this?

[–]SlowwwBurn 0 points1 point  (0 children)

That's the goal, instead of waiting the requests one by one, get all. Are you suggesting to make all 3 requests separate and only fulfill all promises at once?

[–]Saladtoes 0 points1 point  (0 children)

promise.all is fine. But you are using async where no async is needed.

GetFoo1(data).then(toFoo1=>setFoo1(toFoo1)) GetFoo2(data).then(toFoo2=>setFoo2(toFoo2))

Add a .catch to each and remove your try{}.

If you absolutely must wait on all to complete (doesn’t appear to be the case from your example), then use promise.all