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.
Previously, the translating routine looked as follows:
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.
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.
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
Now we can create a temporary callback function that will wait for both responses:
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:
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:
The code could be even cleaner when using