Gautham Renganathan
Gautham Renganathan

Reputation: 645

How to abstract asynchronous behaviour of a ajax request like Ember.js does?

Is there any library that abstracts away the asynchronous behavior of XHR requests? Was watching the below video.(Ember.js intro). Would be great if I can just get the asynchronous abstraction feature alone from Ember's router class. Also, any direction on how this is done would also be great

https://www.youtube.com/watch?v=1QHrlFlaXdI

(around 23:00 mins),

An example,

var model=[];
var obj = {
getModel: function(){
       if(!model.length){
            // sendRequest and store the response in model and
           //  return it
       }else{
           return model;
        }
}
}

http://jsfiddle.net/4YQ4W/

So, in this example, obj.getModel() should get me the model, irrespective of whether it is served from server or not.

Thanks!

Upvotes: 1

Views: 731

Answers (1)

Björn Roberg
Björn Roberg

Reputation: 2366

One of the patterns designed to add a level of abstraction to sync/async behaviour is the Promises/A+ specification, and one popular implementation is Kris Kowal's Q

It lets you write async code that behaves in a predictable and easy to control manner.

an example from the readme:

return getUsername()
.then(function (username) {
    return getUser(username);
})
.then(function (user) {
    // if we get here without an error,
    // the value returned here
    // or the exception thrown here
    // resolves the promise returned
    // by the first line
});

where getUserName is a function returning a promise.

So, in your case, it could be like:

getModel: function(){
    var d = Q.defer();
    if(!model.length){
    // pass the `resolve` function as success callback to the ajax request.
    // pass the `reject` function as fail callback to the ajax request.
        ajaxGetModel(url, d.resolve, d.reject)
    } else {
        d.resolve(existingModel);
    }

    return d.promise;
}

then you can

getModel().then(function(modelObject) { ... } );

This way, the consumer of your API will not need bother about whether your implementations are sync or async, since it's always handled in a consistent way.

Edit: OK, so I dug around a bit in the source of Ember and found that Ember do indeed implement a form of promises API in the sub-module ember-runtime in a class called Deferred, which i suspect is what is used in your question.

Upvotes: 3

Related Questions