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.

My related project

E-book: How to set up free WordPress platform for IT blogs

Do you want to set up a typical blog but you don’t know how to start, which plugins to use or how to customize the site? I spent a few weeks in total doing that from scratch – from learning the ecosystem to adjusting the platform to my very specific needs. Now I want to share with my experience and make the start easier for you.

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.

0 0 votes
Article Rating

Want more?

Share!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x