0

I am trying to return a list when its updated by Jax call but its not working .

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

}

so right now in my getCardList function I have added setTimeout that is because if I tried to do without timeOut some thing like this

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

I was getting empty list ;

I am new to OOPS in js , would be great if you guys could help

Thanks

Andreas
  • 21,535
  • 7
  • 47
  • 56
Vikram Anand Bhushan
  • 4,836
  • 15
  • 68
  • 130

1 Answers1

0

This my approach using a function:

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

If you need a class to do this, the class still need to use a promise or a callback

Sebastián Espinosa
  • 2,123
  • 13
  • 23
  • You don't need `new Promise(...)`. Just return the result of `$.get(...)` or `$.post(...)`: _"As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() **implements the Promise interface**, ..."_ – Andreas May 25 '17 at 09:25
  • Thats even better, i was not sure if jquery uses promises – Sebastián Espinosa May 25 '17 at 09:27
  • @Andreas and https://jsfiddle.net/2s2p4qnc/ can you look into this fiddle , see the ep_list class I am using in multiple other class to fetch the ajax details . – Vikram Anand Bhushan May 25 '17 at 09:31