Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

javascript - Prefer way of doing multiple dependent ajax synchronous call

I have seen different ways of doing multiple dependent ajax synchronous call. Two of which is being widely adopted is the jquery defer method and callback on success.

My question is:
1) What is the advantage of using one over another?
2) In what situation is one is preferred over another?
3) Is there any other better method than these 2?

// jquery defer method
var defer = $.when(
    $.get('ajax_call_1');
);

defer.done(function () {
    $.get('ajax_call_2');
});



// callback on success
$(function(){ 
    $.ajax({
      url:'/ajax_call_1',
      data: {  },
      success: function(data){      
        $.get('ajax_call_2');
      }
    });
  }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Some reasons to use Promises over Callbacks:

  1. Much simpler to sequence multiple asynchronous operations.
  2. Much simpler to build conditional logic involving multiple asynchronous operations.
  3. Much simpler to do robust error handling involving multiple asynchronous operations.
  4. Much simpler to build reusable asynchronous interfaces.
  5. Much simpler to interface with other asynchronous interfaces.
  6. Much simpler to deal with exceptions that might occur deep in asynchronous code that would otherwise cause silent failure

In your question, the simplest way to sequence jQuery Ajax calls and catch all possible errors is to use the natural promises returned from $.ajax() and chain them:

$.get('ajax_call_1').then(function(value) {
    return $.get('ajax_call_2');
}).then(function(result) {
    // success with both here
}, function(err) {
    // error with one of them here
});

Or, with no error handling like in your example:

$.get('ajax_call_1').then(function(value) {
    $.get('ajax_call_2');
})

There is no reason to use this construct here:

// jquery defer method
var defer = $.when(
    $.get('ajax_call_1');
);

because $.get() already returns a promise so there is no need to use $.when() to just create yet another promise. $.when() is useful when you have more than one promise and you want to know when all of them are done. For one promise, you just use it directly - no reason to use $.when() with a single promise.


You can do it your second way:

// callback on success
    $.ajax({
      url:'/ajax_call_1',
      data: {  },
      success: function(data){      
        $.get('ajax_call_2');
      }
    });

As this is just the non-promise way of coding with nested callbacks. The major disadvantage is that propagation of errors and sequencing multiple operations gets messy and difficult when not using promises. In just this simple example, try to get the error from either of the ajax calls back to the caller. It takes a lot of extra code to do that. My promise example above propagates all errors back to the caller for you.


As for your specific questions:

1) What is the advantage of using one over another?

You're basically asking why use promises over nested callbacks. There are hundreds of articles on the advantages of using promises. I will see if I can find one or two, but a Google search for "why promises vs. callbacks" should get you started on some reading.

What’s so great about JavaScript Promises?

Staying Sane with Asynchronous Programming

Why Am I Switching to Promises

2) In what situation is one is preferred over another?

I know of no reason why plain nested callbacks is preferred over using promises. Once you have learned promises, you will pretty much always find them a better way to code. The only reason I would not use promises is if I was trying to make code that was compatible with old browsers that did not have promises and even then, I'd probably just include a polyfill so that promises were supported.

3) Is there any other better method than these 2?

Yes, see my first code example.


P.S. Note that I choose to only use .then() with jQuery promises because that is the ES6 promise standard and it will make it easier in the future when jQuery transitions its promises to be more standards-compatible (which they are working on). Your code will also be more consistent when interfacing with other sources of promises that do use the standard.

P.P.S. Promises are one-shot devices. They either resolve or reject once and only once. If you are trying to get multiple notifications from some source, then promises are not built for that. An event emitter or a publish/subscribe system might be a better match for that type of problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...