0

I want that my function emitirFatura() wait for my function atualizarEncomenda ended to execute redirectFatura(), but its not working.

function emitirFatura(id){
    atualizarEncomenda(id).then(redirectFatura(id));
}

function redirectFatura(id){
    window.location = "index.php?menu=admin&submenu=fatura&control=emitir&encomenda="+id;
}

function redirectFatura(id){
    window.location = "index.php?menu=admin&submenu=fatura&control=emitir&encomenda="+id;
}

function atualizarEncomenda(id){
d = $.Deferred();
var formData = 'id='+id;

$.post("admin/updEncomenda.php", formData , function(data)
{           
   if (data != '' || data != undefined || data != null){ 
      $('#sending-control').html('<div align="center"><img src="../../img/checked.gif"  width="50px"/></div>');
      setTimeout(function(){ $('#sending-control').html('');}, 4000);
      d.resolve;
   }else{
      $('#sending-control').html('<div align="center"><img src="../../img/error.gif"  width="50px"/></div>'); 
      setTimeout(function(){ $('#sending-control').html('');}, 4000);
   }
});
return d.promise();
}
Shiladitya
  • 11,210
  • 15
  • 22
  • 33
Rui Silva
  • 3
  • 1

1 Answers1

0

For starters, actualizarEncomenda is returning d before a response from the ajax request has changed it's value or state. A return statement is expected in front of the $.post if you want to return the promise. Deffered is a promise object itself. So to return the promise without resolving it only d has to be returned.

Resolve is a function, so should be d.resolve().

When the promise is resolved you probaply want to return the resolved promise.

So something like this should do it:

function atualizarEncomenda(id){
    d = 

    $.Deferred();
    var formData = 'id='+id;

    return $.post("admin/updEncomenda.php", formData , function(data)
    {           
       if (data != '' || data != undefined || data != null){ 
          $('#sending-control').html('<div align="center"><img src="../../img/checked.gif"  width="50px"/></div>');
          setTimeout(function(){ $('#sending-control').html('');}, 4000);
          return d.resolve();
       }else{
          $('#sending-control').html('<div align="center"><img src="../../img/error.gif"  width="50px"/></div>'); 
          setTimeout(function(){ $('#sending-control').html('');}, 4000);
       }
       return d;
    });
}

Hope this helps!

Wijnand
  • 1,144
  • 3
  • 16
  • 28
  • Still not waiting for atualize the DB before redirect – Rui Silva Dec 12 '17 at 14:54
  • You can use [this](https://stackoverflow.com/questions/39538473/using-settimeout-on-promise-chain) trick to put your setTimeout in a promise chain. Then you would get something like this `$('#sending-control').html('...'); delay(4000).then($('#sending-control').html('')).finally(return d.resolve())`: – Wijnand Dec 13 '17 at 14:07