Waiting for two parallel callbacks

Waiting for two parallel callbacks

While trying to enhance a Chrome plugin that translates text on pages (GitHub), I wanted to show two translations at once – of the pointed word and of the entire sentence or paragraph. Technically it was not hard except for the part of retrieving two translation results and displaying them in one popup.

Background

Previously, the translating routine looked as follows:

JS
background.js

Here, AJAX sends the word and calls the onresponse() method with the translation.

In order to support translating two phrases, two parallel calls have to be done and their results should be somehow merged.

Method 1

One option is to make two AJAX calls, collect the responses, and once we have all responses, call the actual callback.

First, we need a new parameter sentence and another options object for it. It’s worth using the feature to clone JavaScript objects to reduce code duplication:

JS
background.js

Now we can create a temporary callback function that will wait for both responses:

JS

However, because the second phrase to translate (sentence) is optional, we have to follow the new routine only if it was provided. Below you can find the complete code for that function:

JS
background.js

Method 2

The documentation of the $.ajax method states that:

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise

And Promises provide very neat support for waiting and merging. Namely, there is the Promise.all() method that waits for an array of promises to be fulfilled (docs).

This enables us to remove the new temporary callback and use Promises to wait for responses (only one if sentence is empty, two otherwise). Additionally, the `success` callbacks in options were also unnecessary:

JS
background.js

The code could be even cleaner when using async/await.

Leave a Reply

avatar
  Subscribe  
Notify of