如何在 JS 中编写 promise 以仅在 ajax req 完成时才返回数据



当 Jax 调用更新它时,我正在尝试返回一个列表,但它不起作用。

class ep_List {
  constructor() {
    this.urlForAjax = '';
    this.dataList = [];
    this.dataJson = '';
    this.dataParams = {};
    this.cardList = [];
  }
  getData(method, params, url) {
    this.urlForAjax = url;
    this.dataParams = params;
    if (method == 'get')
      this.callGetAjax();
    else
      this.callPostAjax();
  }
  callPostAjax() {
    $.post(this.urlForAjax, this.dataParams, this.setList.bind(this));
  }
  callGetAjax() {
    $.get(this.urlForAjax, this.setList.bind(this));
  }
  setList(res) {
    this.dataList = res;
    ajaxPromise = true;
  }
  getCardList() {
    var that = this;
    setTimeout(function() {
      return this.cardList = createCardList(that.dataList);
    }, 3000);
  }
}

所以现在在我的getCardList函数中我添加了setTimeout那是因为如果我尝试不超时,像这样的事情

var listObj = new ep_List();
listObj.getData('get', '', url);
listObj.getCardList();
console.log(listObj.cardList);

我得到空列表;

我是 js 中的 OOPS 新手,如果你们能提供帮助,那就太好了

谢谢

这是我

使用函数的方法:

function getData(method, params, url) {
  return new Promise(function(resolve, reject){
    if(method == 'get') {
      $.get(url, params, function(res){
        resolve(res);
      });
    }
    else {
      $.post(url, function(res) {
        resolve(res);
      });
    }
  });
}
//You call this like this
getData('post', 'the_url', { the: 'params' }).then(function(res){
  //Use the response on something.
  console.log(res);
});

如果你需要一个类来做到这一点,该类仍然需要使用承诺或回调

最新更新