Tengo una función JS simple definida así:
function firstFunction() { $.ajax({ url: "/path/to/my/endpoint", type: "GET" }).done(function (data) { localStorage.setItem("myItem", data); }); }Más adelante, tengo otra función definida así:
function mySecondFunction() { if(localStorage.getItem("myItem") == null) { // Here I want to call firstFunction() and stop everything until it finishes } //Immediately use localStorage.getItem("myItem") for other purposes //no matter I entered the if() or not } Con un simple async: false en $.ajax , funciona, pero he visto que quedará en desuso y quiero evitar esta solución .
¿Podría sugerir cómo esperar mySecondFunction al ingresar my if() ?
Intenté con $.when() pero sin éxito, ¿quizás hice algo mal?
Probé algo como
function mySecondFunction() { var deferred = $.Deferred(); if(localStorage.getItem("myItem") == null) { $.when(firstFunction()).then(function () { deferred.resolve(); }) } else { deferred.resolve(); } //other instructions } Pero other instructions se llaman ANTES del final de firstFunction()
Haz firstFunction() devuelva una promesa.
function firstFunction() { return new Promise((res, err) => { $.ajax({ url: "/path/to/my/endpoint", type: "GET" }).done(function (data) { localStorage.setItem("myItem", data); res() }); }); } Hacer mySecondFunction aysnc.
async function mySecondFunction() { if(localStorage.getItem("myItem") == null) { await firstFunction(); } localStorage.getItem("myItem") ... }Así es como le recomendaría que hiciera esto, ya que la solicitud ajax no bloqueará la ejecución de otro código, como las devoluciones de llamada de botón. Async/await y las promesas son difíciles de entender al principio, así que aquí hay algunas lecturas sobre cómo funcionan detrás de escena.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
Simplemente cambie sus cláusulas if con un ciclo while y llame a su firstFunction en ese ciclo.
Ejemplo:
function mySecondFunction() { while(localStorage.getItem("myItem") == null) { firstFunction() } }