微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Javascript:将AJAX结果保存为Class变量

我知道 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
}

在上面的代码中,需要在ajax成功回调中调用需要访问data属性函数,所以如果我有十个需要数据的方法,我将不得不在回调之前将所有这些方法不觉得是正确的.如何最大程度地减少回调中的函数数量,并以其他一些方式确保函数成功并保存数据实例变量数据.

解决方法

最重要的部分是如何使用JavaScript处理异步数据.有一些经过很好测试的解决方案:功能和承诺.

在两个cass中,Reader应该有一个构造函数来分配这样的数据:

function Reader(data) {
   this.data = data;
}

回调方法需要一个具有回调函数的工厂函数.

function getReader(url,callBack) {
   Ajax.success(function(data){
      callBack( new Reader(data) );
   });
}

并使用它

getReader(url,function(reader) {
    reader.searchData();
});

Promise -approach不需要立即回调,所以结果可以存储在一个变量中,并作为一个变量传递,这个变量有一些优点:

function getReaderPromise(url) {
   return new Promise( function( resolve,reject ) {
     Ajax.success(function(data){
      resolve( new Reader(data) );
     });    
   });
}

然而,使用承诺通常需要调用那个承诺的功能

getReaderPromise(url).then( function(reader) {
    reader.searchData();
});
// Fat arrow Syntax
getReaderPromise(url).then( (reader) => {
    reader.searchData();
});

在将来,您可以使用具有收益的ES6发生器的Promises来消除回调

let reader = yield getReaderPromise( url );

如下所述:https://davidwalsh.name/async-generators

原文地址:https://www.jb51.cc/ajax/153609.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐