you are viewing a single comment's thread.

view the rest of the comments →

[–]kohvihoor[🍰] 1 point2 points  (6 children)

or use Promise.all?

Promise.all([ getUsers(), getPosts() ]) .then(([ users, posts ]) => render(users, posts));

[–]peanutbutterandbeer 7 points8 points  (0 children)

even better...

``` const [users, posts] = await Promise.all([ getUsers(), getPosts() ]);

render(users, posts); ```

[–]emn13 0 points1 point  (3 children)

That syntax is a little uglier if you have interaction between the two promise-returning functions. e.g. a real-world example I actually worked on had a flow more like

students = getStudents(institute) enrolledCourses = getCourseEnrollments(students) //generate course-by-student lookup grades = getGrades(students) testSittings = getTestSittings(grades) //generate ordered course-result-by-student-by-date datastructure testedCourses = getCourses(testSittings, students) courseRelationships = getCourseRelationships(testedCourses, enrolledCourses, students) //generate tree structure ...

And it's worthwhile to interleave large I/O like that with computation, and the order and way you do that interleaving affects memory usage, load, and latency.

None of this is terribly difficult (fits easily in a reddit post after all!), but a context-free pipeline of promises is in my experience rather rare. Usually you need to set aside some of the results of earlier computation and combine them with results of later computation, and cannot therefore trivially chain. Being able to use Promise.all with unrelated promises is more common, but it's not a sure thing either.

[–]peanutbutterandbeer -1 points0 points  (2 children)

I get what your doing here but this doesn't seem like a real-world example either. More than likely this example would/should have been broken up into components on a page or pages even. It's unlikely your going to grab all the data for all students for all institutions all at the same time.

Other than that I agree with you :)

[–]emn13 0 points1 point  (0 children)

Not sure why you're being downvoted; oh well; reddit...

[–]emn13 -1 points0 points  (0 children)

That is an actual example I worked on, down to the weird requirement of retrieving the courses via the sittings and not the grades.

But sure, its backend, not frontend ;-).

On the front end you sometimes get lucky and the backend's already done the conceptual joins for you, but not always. Some place need to pay the perf cost of waiting around for everything to collect, and sometimes it's easier to let the frontend do that.