最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Best way of structuring Javascript If statements to be synchronous in a function - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Aug 8, 2015 at 18:29 bcan001bcan001 1471 gold badge1 silver badge7 bronze badges 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. – kockburn 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. – jfriend00 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. – thelittlegumnut 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. – Bergi Commented Aug 8, 2015 at 18:39
Add a ment  | 

2 Answers 2

Reset to default 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:

  • How do I chain three asynchronous calls using jQuery promises?
  • Chain of Jquery Promises

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 inpatible (jQuery, Angular, Ember)
  3. They are a new concept to learn so the learning curve will be a little steep for newers.

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.

发布评论

评论列表(0)

  1. 暂无评论