如何像Ember.js那样抽象ajax请求的异步行为

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

本文关键字:请求 异步 ajax 抽象 Ember 何像 js      更新时间:2023-09-26

是否有任何库可以抽象掉XHR请求的异步行为?正在观看以下视频。(Ember.js介绍)。如果我能从Ember的路由器类中单独获得异步抽象功能,那就太好了。此外,任何关于如何做到这一点的方向都将是伟大的

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

(大约23:00分钟),

一个例子,

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/

因此,在本例中,obj.getModel()应该为我获取模型,而不管它是否从服务器提供。

谢谢!

为同步/异步行为添加抽象级别而设计的模式之一是Promises/a+规范,其中一个流行的实现是Kris Kowal的Q

它允许您编写异步代码,以可预测且易于控制的方式进行操作。

自述文件中的一个示例:

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
});

其中CCD_ 1是返回承诺的函数。

所以,在你的情况下,它可能是这样的:

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;
}

然后你可以

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

这样,API的使用者就不需要关心您的实现是同步的还是异步的,因为它总是以一致的方式处理的。

编辑:好吧,我在Ember的源代码中挖掘了一下,发现Ember确实在名为Deferred的类的子模块ember-runtime中实现了一种形式的promise API,我怀疑这就是你的问题中使用的内容。