Jam*_*rge 10 javascript ajax jquery callback
我知道javascript不使用Class,至少不是常识.我想知道如何在类变量中返回并保存AJAX返回值,而不是在回调中调用多个方法.
var Reader = function(){
//Initialize some variables
this.data = null;
}
Reader.prototype.makeAjaxCall = function(urlPath){
//Make and Ajax call and return some value
Ajax.success(function(data){
this.data = data;
});
}
Reader.prototype.searchData = function(param){
//Needs access to this.data
}
Reader.prototype.findData = function(id){
//Needs access to this.data
}
Reader.prototype.deleteItem = function(id){
// Needs access to this.data
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,需要data在内部调用需要访问属性的任何函数ajax success callback,所以如果我有十个需要数据的方法,我将不得不在回调中排列所有这些,我感觉不对.如何最小化回调中的函数数量,并以其他方式确保函数成功并将数据保存为实例变量data.
最重要的部分是如何使用JavaScript处理异步数据.有一些经过良好测试的解决方案:功能和承诺.
在两个cass中,Reader应该有一个构造函数,它可以像这样分配数据:
function Reader(data) {
this.data = data;
}
Run Code Online (Sandbox Code Playgroud)
回调方法需要一个具有回调的工厂函数.
function getReader(url, callBack) {
Ajax.success(function(data){
callBack( new Reader(data) );
});
}
Run Code Online (Sandbox Code Playgroud)
并使用它
getReader(url, function(reader) {
reader.searchData();
});
Run Code Online (Sandbox Code Playgroud)
Promise -approach不需要立即回调,因此结果可以存储在变量中并作为变量传递,具有一些优点:
function getReaderPromise(url) {
return new Promise( function( resolve, reject ) {
Ajax.success(function(data){
resolve( new Reader(data) );
});
});
}
Run Code Online (Sandbox Code Playgroud)
但是,使用promise通常需要调用promise的then函数:
getReaderPromise(url).then( function(reader) {
reader.searchData();
});
// Fat arrow syntax
getReaderPromise(url).then( (reader) => {
reader.searchData();
});
Run Code Online (Sandbox Code Playgroud)
将来你可以使用ES6生成器以及类似的收益来消除Promises的回调
let reader = yield getReaderPromise( url );
Run Code Online (Sandbox Code Playgroud)
如下所述:https://davidwalsh.name/async-generators
你可以做类似的事情
Reader.prototype.searchData = function(param){
var self = this;
if (!this.data) {
setTimeout(function() { self.searchData(param) }, 1000);
return;
}
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1754 次 |
| 最近记录: |