Question

In my ZenDesk app, I:

  1. retrieve some identifying information from the ticket and requester
  2. make several requests to another web service
  3. modify the ticket with the combined results

Using plain jQuery, you'd coordinate this using jQuery.when(deferreds) to trigger step 3 once all of the requests in step 2 are complete:

$.when($.ajax("/page1"), $.ajax("/page2"))
    .done(function(page1result, page2result) { 
        // modify the ticket with the results
    });
  1. Is jQuery.when() available in an App? (I tried this.$.when() with no luck.)
  2. If not, what's the preferred way to accomplish something similar? (Perhaps using Promises directly?)
Was it helpful?

Solution

jQuery.when() is available through the application object as this.when(). Here's a simple example (framework version 0.5) that creates a couple trivial promises (using this.promise(), similar to jQuery.Deferred()) then waits until they have succeeded/resolved to invoke a third function.

Substitute this.ajax(...) for this.createPromise() to do real work.

app.js

(function() {
    return {
        onActivate: function() {
            var promises = []

            promises.push(this.createPromise().done(function() {
                console.log('promise 1 done');
            }));

            promises.push(this.createPromise().done(function() {
                console.log('promise 2 done');
            }));

            this.when.apply(this, promises).done(function() {
                console.log('all promises done');
            });
        },

        // returns a promise that always succeeds after 1 sec.
        createPromise: function() {
            return this.promise(function(done, fail) { 
                setTimeout(done, 1000);
            });
        },

        events: {
            'app.activated': 'onActivate'
        }
    };
}());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top