6

I'm asking this question so I can learn the 'best practice' way of doing something in javascript. Say I have this code here:

var someFunc = function () {
  if (something) {
    // do something
  }
  if (somethingElse) {
    // do somethingElse
  }
};

The question is what would be the best way to ensure that the 'something' is always ran BEFORE the 'somethingElse'. Since javascript is asynchronous, I understand that I would need some sort of callback system to ensure this. However, is there an easier way to refactor this? What if there are many if statements? What are the best libraries to do something like this cleanly? Thanks in advance.

4
  • 5
    Since javascript is asynchronous is wrong. Only certain methods (such as setTimout, setInterval, XMLHTTPRequets, requestframe, etc) are asynchronous. Standard javascript code is synchronous. Commented Aug 8, 2015 at 18:30
  • Only specific operations in javascript are asynchronous and we can only help you sequence a specific asynchronous operation if you show us the code for that specific operation. There is no generic answer without seeing how the specific asynchronous operation works. Callbacks are likely involved, but specifics are needed in order to help. Commented Aug 8, 2015 at 18:31
  • I'm pretty sure that JavaScript isn't asynchronous in the same way that you might think of threads. I think the most asynchronous JavaScript can ever get is when you load multiple source files asynchronously in an HTML file, or run specific functions such as requestAnimationFrame. So those if statements you mention above should be executed one after the other. No need for callbacks. Commented Aug 8, 2015 at 18:32
  • I'm voting to close this question as off-topic because it is based on a false premise. Be more specific about something and do something and how they are asynchronous to get help with this. Commented Aug 8, 2015 at 18:39

2 Answers 2

10

Not all lines of code run asynchronously in Javascript. It depends on your code. For example:

var someFunc = function () {
  if (something) {
    console.log('something');
  }
  if (somethingElse) {
    console.log('something else');
  }
};

Will always write the following output:

something
something else

However if instead of printing the values you are calling a function that will be run later (like an Ajax request or a setTimeout callback), there is no guarantee that your code is run in the exact order. This behaviour depends on the function you are calling. For example the JQuery $.get() function is asynchronous (which means it will call your function at a later time that is not in your control) like this:

var someFunc = function () {
  if (something) {
    $.get('some-file.txt').done(function (result) {
      console.log(result);
    });
  }
  if (somethingElse) {
    $.get('some-other-file.txt').done(function (result) {
      console.log(result);
    });
  }
};

The resulting output can be the contents of 'some-file.txt' and 'some-other-file.txt' in any other.

As a rule of thumb whenever you are passing a function to another function (callbacks) you may be using the asynchronous feature of Javascript.


Nested callbacks

One way to solve this issue is to call the second asynchronous call in the first function:

var someFunc = function () {
  if (something) {
    $.get('some-file.txt').done(function (result1) {
      console.log(result1);
      if (somethingElse) {
        $.get('some-other-file.txt').done(function (result2) {
          console.log(result2);
        });
      }
    });
  }
};

But as you might have guessed this code will be hard to read.


Promises to the rescue

With Promises you can have a code that is easier to read.

Let's write the above ugly code with promises:

var someFunc = function () {
  if (something) {
    $.get('some-file.txt').then(function (result1) {
      console.log(result1);
      if (somethingElse) {
        return $.get('some-other-file.txt');
      }
    }).then(function (result2) {
        console.log(result2);
    });
};

In general, promises make the code more readable and avoid too many nested callbacks. You can chain promises and it will read like synchronous code but it actually runs asynchronously.

See these questions to get more information:

What's the catch with promises?

  1. They are not supported in old browsers (but you can add them with a 3rd party library like ES6 Promise Polyfill.
  2. Before the promises were officially standardized every library had their own implementation which are slightly incompatible (jQuery, Angular, Ember)
  3. They are a new concept to learn so the learning curve will be a little steep for newcomers.
Sign up to request clarification or add additional context in comments.

3 Comments

If it answers your question, please mark it as answer so that I can get points :) Thank you.
thanks! yeah that really answered my issues I've been having... the info on promises is also going to be helpful in the future
As a side-note, jQuery 3.0 Deferred objects are now actually Promises/A+ compatible.
1

Javascript is not asynchronous.

Provided both the if conditions are satisfied, what is inside the first if will get executed first and then the contents of the second if will be executed.

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.