Ajax request in ES6 constructor

0

How do I make a Ajax request in my constructor and assign the values of this request to my attributes?

So far it's like this and it's not working, I'm returning 2 jsons ... on console.log the attributes are empty, ie the assignment is not being done, the query usually works there in my PHP , I already tested.

The console does not display anything Using Promisse:

    class pergunta {
      constructor(perguntas, respostas, desafios) {
          return new Promise((perguntas, respostas, desafios) => {
              jQuery.ajax({
                  url: '../php/consulta.php' + location.search,
                  type: "GET",
                  dataType: 'json',
                  success: (pergunta, resposta, desafio) => {
                      this.perguntas = pergunta.pergunta;
                      this.respostas = pergunta.resposta;
                      this.desafios = desafio.descricao;
                  }
              });
          });
      }
  }

  new pergunta().then((perguntas) => {
      console.log(pergunta);
  });
    
asked by anonymous 01.05.2017 / 04:32

2 answers

2

You have 2 problems here:

    Ajax is asynchronous, you can not #1 after instantiating the class, because this happens before the replies come from the server.

# 1:

Within this #2 points to jQuery, not to what's around. So if you want to have console.log pointing to your class you have 3 alternatives:

  • use the success: function(pergunta, desafio){ property and pass in the context reference you want:

Example:

jQuery.ajax({
   url: '../php/consulta.php' + location.search,
   type: "GET",
   dataType: 'json',
   context: this,
   success: function(pergunta, desafio){
       this.perguntas = pergunta.pergunta;
       this.respostas = pergunta.resposta;
       this.desafios = desafio.descricao;

     }
});
  • You can use this / this , giving the name context to this out of sósia of jQuery to have a pointer after (the idea that Heber also suggested ).

Example:

const self = this;
jQuery.ajax({
   url: '../php/consulta.php' + location.search,
   type: "GET",
   dataType: 'json',
   success: function(pergunta, desafio){
       self.perguntas = pergunta.pergunta;
       self.respostas = pergunta.resposta;
       self.desafios = desafio.descricao;
     }
});
  • use alias that does not change the execution context:

Example:

jQuery.ajax({
   url: '../php/consulta.php' + location.search,
   type: "GET",
   dataType: 'json',
   success:(pergunta, desafio) => {
       this.perguntas = pergunta.pergunta;
       this.respostas = pergunta.resposta;
       this.desafios = desafio.descricao;
     }
});

# 2:

Here you have to use callbacks , promises or self / success

An example with Promisses might look like this:

class pergunta {
    constructor(id, title) {
        return new Promise((res, rej) => {
            jQuery.ajax({
                url: '../php/consulta.php' + location.search,
                type: "GET",
                dataType: 'json',
                success: (pergunta, desafio) => {
                    this.perguntas = pergunta.pergunta;
                    this.respostas = pergunta.resposta;
                    this.desafios = desafio.descricao;
                }
            });
        });
    }
}

new pergunta().then((perguntas) => {
    console.log(perguntas);
});

Demo with promisse:

class pergunta {
  constructor(id, title) {
    return new Promise((res, rej) => {
      jQuery.ajax({
        url: 'https://jsonplaceholder.typicode.com/posts/1',
        type: "GET",
        dataType: 'json',
        success: ({
          id,
          title
        }) => {
          this.id = id;
          this.title = title;
          res(this);
        }
      });
    });
  }
}
new pergunta().then((perguntas) => {
  console.log(perguntas);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
01.05.2017 / 09:13
1

The scope of the success function of the ajax request is different from the scope of the constructor, try this:

class pergunta {

      constructor(perguntas = [], respostas = [], desafios = [], valor = 100, posicao = 0){

        var _self = this;

        [.. código suprimido ..]

        jQuery.ajax({
           url: '../php/consulta.php' + location.search,
           type: "GET",
           dataType: 'json',
           success: function(data){
               _self.perguntas = data.perguntas;
               _self.respostas = data.respostas;
               _self.desafios = data.desafios;
           }
        });
    }
}
const perguntas = new pergunta();
console.log(perguntas);

Also remember that it is an asynchronous method, so it will only "fill in" the value after the request has finished.

    
01.05.2017 / 07:20