Problem with asynchronism [duplicated]

1

I have a function like this:

function pru1(){
    var temp1=pru2('Chocolate');
    if(temp1){
     alert('Chocolate');
    }else{
     alert('Nope');
    }
}

function pru2(element){
    $.get('/listaElementos.php',{
                funcion:'listar',
                element:element
            }).done(function(data){
              return data;
            });
}

The problem is that I evaluate temp1 before pru2 answers, as I could do to ensure the response of pru2 before evaluating with the if ?.

    
asked by Quarkbite 23.10.2017 в 16:22
source

2 answers

1

You can not return from a callback to the outside because it is another scope / scope of execution. You can use a callback or return a promise.

Callback

function pru2(element, cb){
  $.get('/listaElementos.php',{
    funcion:'listar',
    element:element
  }).done(function(data){
    cb(data);
  });
}

function pru1() {
    pru2('Chocolate', function(temp1) {
      if(temp1){
        alert('Chocolate');
      } else{
       alert('Nope');
      }
    });
}

Promise

function pru2(element, cb) {
  return new Promise((resolve, reject) => {
    $.get('/listaElementos.php', {
      funcion:'listar',
      element:element
    }).done(function(data) {
      resolve(data);
    }).fail(function(jqxhr, error, status) {
      reject(error);
    });
}

function pru1() {
  pru2('Chocolate')
    .then((temp1) => {
      if(temp1) {
        alert('Chocolate');
      } else {
       alert('Nope');
      }
    })
    .catch(err => console.error(err));
}

// o usando async/await
async function pru1() {
  try {
    const temp1 = await pru2('Chocolate');
    if(temp1){
      alert('Chocolate');
    } else{
      alert('Nope');
    }
  } catch (e) { console.error(e); }
}
    
answered by 23.10.2017 / 17:02
source
0

What happens is that Javascript will execute "linearly" everything you put in a single function. A pru1 does not care (or rather does not know ) that pru2 will return a value.

What you need to do is learn how to use the callbacks that provides the language to do so. The most direct example is in the $.get where you will wait for the server to respond to execute the path of done if there is no problem.

In short, a callback will be executed once the function ends. An approximation would be:

function pru1(){
  //La función que se pasa como argumento es el callback que se ejecutará al final.
  pru2('Chocolate', function(respuestaCallback){
    if(respuestaCallback){
      alert('Chocolate');
    }else{
      alert('Nope');
    }
  });
}

function pru2(element, callback){
  $.get('/listaElementos.php',{
    funcion:'listar',
    element:element
  }).done(function(data){
    //Una vez que el servidor responda, se invoca a
    //la función pasada como argumento en pru1.
    callback(data);
  });
}
    
answered by 23.10.2017 в 17:08