Promises in Three Languages

January 19, 2025 note-to-self

Three ways to handle concurrent API requests that resolve when all are done, but can run concurrently.

In other words, if you have three requests and

  1. takes 2 seconds,
  2. takes 1 second
  3. takes 2 seconds

They should return together in 2 seconds, not five.

PHP:

React\Promise\all([$promise1, $promise2])->then(function ($results) {
    // $results is an array of the resolved values from all promises
});

Javascript:

Promise.all([promise1, promise2]).then((results) => {
    // results is an array of the resolved values from all promises
});

Python:

results = await asyncio.gather(task1(), task2())

Each of those (all, all, gather) return a new promise that resolves when everything in it (it == all, all, or gather) is finished/resolved.

Then, you have the result of all three and can move on to the next step. You could also do them one by one, but it would take longer.

These posts are for my own understanding. Reader beware. Info may be wrong but it reflects my current understanding.