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

7
  • You don't "wait". You can put the functionality in a callback or use Promises. Commented May 19, 2022 at 17:29
  • I would recommend using promises. Commented May 19, 2022 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 ? Commented May 19, 2022 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) Commented May 19, 2022 at 17:39
  • Does this answer your question? Proper way to wait for one function to finish before continuing? Commented May 19, 2022 at 17:44

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

YOu can allso do firstFuction,then( () => { secondFunction(); } ); calls.then when the promise is resolved.
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()
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.