Home > Net >  Wait for an external JS function before continuing the same method
Wait for an external JS function before continuing the same method

Time:05-20

I have a simple JS function defined like this :

function firstFunction() {
    $.ajax({
        url: "/path/to/my/endpoint",
        type: "GET"
    }).done(function (data) {
        localStorage.setItem("myItem", data);
    });
}

Later on, I have another function defined like this :

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
}

With a simple async: false in $.ajax, it works, but I've seen it's going to be deprecated and I want to avoid this solution.

Could you please suggest how to wait for mySecondFunction when entering my if() ?

I tried with $.when() but without success, maybe I did somehting wrong ?

I tried something like

   function mySecondFunction() {
      var deferred = $.Deferred();

      if(localStorage.getItem("myItem") == null) {
           $.when(firstFunction()).then(function () {
                    deferred.resolve();
                })
      }
      else {
         deferred.resolve();
      }

      //other instructions
    }

But other instructions are called BEFORE the end of firstFunction()

CodePudding user response:

Make firstFunction() return a promise.

function firstFunction() {
    return new Promise((res, err) => {
        $.ajax({
            url: "/path/to/my/endpoint",
            type: "GET"
        }).done(function (data) {
            localStorage.setItem("myItem", data);
            res()
        });
    });
}

Make mySecondFunction aysnc.

async function mySecondFunction() {
    if(localStorage.getItem("myItem") == null) {
        await firstFunction();
    }

    localStorage.getItem("myItem")
    ...
}

This is how I would recommend you do this, since the ajax request wont block execution of other code, like button callbacks. Async/await and promises are hard to grasp at first, so here's some reading on how they work behind the scenes.

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

CodePudding user response:

Just change your if clauses with a while loop and call your firstFunction in that loop.

Example:

function mySecondFunction() {
    while(localStorage.getItem("myItem") == null) {
        firstFunction()
    }
}
  • Related