0

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()

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
user2687153
  • 427
  • 5
  • 24
  • You don't "wait". You can put the functionality in a callback or use Promises. – Pointy May 19 '22 at 17:29
  • I would recommend using promises. – Derek Lawrence May 19 '22 at 17:30
  • @DerekLawrence I tried using $.Deferred();, then resolve it afer the call to firstFunction() but it doesn't wait ; maybe I did something wrong ? – user2687153 May 19 '22 at 17:35
  • @Pointy you're right, but please take a look to my edit, it's what I tried but it looks incorrect (at least as I wrote it) – user2687153 May 19 '22 at 17:39
  • Does this answer your question? [Proper way to wait for one function to finish before continuing?](https://stackoverflow.com/questions/21518381/proper-way-to-wait-for-one-function-to-finish-before-continuing) – Heretic Monkey May 19 '22 at 17:44
  • Please don't add titles like *EDIT* to your question; Anyone can view the edit history of your question if it interests them. – Heretic Monkey May 19 '22 at 17:45
  • @HereticMonkey Interesting, I'm gonna take a look. Surprisingly I haven't found this question during my searches... Thanks for pointing it out – user2687153 May 19 '22 at 17:55

2 Answers2

2

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

kalkronline
  • 459
  • 2
  • 12
0

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()
    }
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
SurpriseMF
  • 174
  • 9