Execute function when another is completed

1

I am trying to execute a function when another one is completed but apart from that I have no idea how to do it. By the way that I am going I get a syntax error and I do not understand the reason very well.

This is the way I'm trying to do it:

$.when( Ventanica('Articulos.php','Articulos','1100','700','Gestión de Articulos'); ).then(function() { VerMas('Inarticulos','Articulos','modificar','modificar_articulos',IdArticulo); });

Ventanica opens a dialog of jquery ui and loads a web inside and see more opens the article in question within that dialog.

Is this the way to do it? he only executes the first function and of the second he passes olympically

    
asked by Killpe 17.01.2018 в 18:45
source

1 answer

2

When using jQuery.when the output is a thenable object or a "promise" (although the promises of jQuery are a bit sui generis). If you invoke when by passing an argument that does not return a promise or a jQuery.Deferred , the first part of when is resolved immediately.

Look at the following example. We have a function that returns immediately. Using when with it will execute then instantly.

We have another function that returns a promise, which is resolved 2 seconds later, via a setTimeout . In the second case, as the function returns a promise, the when effectively remains waiting for the resolution of the promise.

function imprime_inmediato() {
  var ahora=(new Date()).toISOString().split(/[T|\.]/)[1];
  console.log('retorno inmediato empieza a las',ahora);
}
function imprime_diferido(texto) {
  var d1 = $.Deferred();
  var ahora=(new Date()).toISOString().split(/[T|\.]/)[1];
  console.log('retorno diferido empieza a las',ahora);
  window.setTimeout(function() {
    d1.resolve();
  },2000);
  return d1.promise();
}


function terminado(tipo) {
  var ahora=(new Date()).toISOString().split(/[T|\.]/)[1];
  console.log(tipo,'terminado a las', ahora);
}

$.when(imprime_inmediato())
  .then(function() { 
    terminado('inmediato');  
   });
   
$.when(imprime_diferido())
  .then(function() { 
    terminado('diferido');  
   });   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

In your case, you want to run VerMas when the popup has finished loading, so that Ventanica should say something like:

function Ventanica(url,windowName,ancho,alto) {
   var d1 = $.Deferred();

   newwindow=window.open(url,windowName,'height='+alto+',width='+ancho);

   newwindow.addEventListener('load',d1.resolve(), true); 

   return d1.promise();
 }

In this way, the function does not return immediately, but returns a promise that is resolved when the popup issues the load event.

The syntax for calling the functions would be:

$.when( Ventanica('Articulos.php','Articulos','1100','700','Gestión de Articulos') )
.then(function() { 
    VerMas('Inarticulos', 'Articulos', 'modificar', 'modificar_articulos', IdArticulo); 
});
    
answered by 18.01.2018 в 17:52