Why are callbacks more “tightly coupled” than promises?

前端 未结 5 1068
Happy的楠姐
Happy的楠姐 2021-01-30 06:51

Can you explain me the following phrase (taken from an answer to Stack Overflow question What are the differences between Deferred, Promise and Future in Javascript?)?

W

5条回答
  •  执笔经年
    2021-01-30 07:34

    A promise is an object that represents the result of an asynchronous operation, and because of that you can pass it around, and that gives you more flexibility.

    If you use a callback, at the time of the invocation of the asynchronous operation you have to specify how it will be handled, hence the coupling. With promises you can specify how it will be handled later.

    Here's an example, imagine you want to load some data via ajax and while doing that you want to display a loading page.

    With callbacks:

    void loadData = function(){
      showLoadingScreen();
      $.ajax("http://someurl.com", {
        complete: function(data){
          hideLoadingScreen();
          //do something with the data
        }
      });
    };
    

    The callback that handles the data coming back has to call hideLoadingScreen.

    With promises you can rewrite the snippet above so that it becomes more readable and you don't have to put the hideLoadingScreen in the complete callback.

    With promises

    var getData = function(){
      showLoadingScreen();
      return $.ajax("http://someurl.com").promise().always(hideLoadingScreen);
    };
    
    var loadData = function(){
      var gettingData = getData();
      gettingData.done(doSomethingWithTheData);
    }
    
    var doSomethingWithTheData = function(data){
     //do something with data
    };
    

    UPDATE: I've written a blog post that provides extra examples and provides a clear description of what is a promise and how its use can be compared to using callbacks.

提交回复
热议问题