How can you use a callback to guarantee sequential execution?

后端 未结 3 1597
夕颜
夕颜 2021-01-28 08:17

I am trying to wrap my head around callbacks and I do not understand how callbacks guarantee that a statement will execute after(in terms of time)

3条回答
  •  无人共我
    2021-01-28 09:19

    You have asked two questions,

    1. Is callback execution sequence guaranteed?

    2. Is callback only respond to events ?

    Answer

    1. Yes.

    From my understanding, callback is just calling another function to be run now (when it is called)

    It is guarantee to run immediately when you call it.

    To ensure something is called before the callback is triggered, simply put the things you want to call execute first before callback is conducted.

    e.g. from your code, by modify it a bit, callback is guarantee to run after the console.log is executed.

    function foo(callback) {
        setTimeout(() => {
            console.log("Do something with unknown time");
            callback();
        }, 2000);
    }
    
    function callback() {
        console.log("Execute callback");
    }
    
    foo(callback);
    

    It is the setTimeout which defers the execution, and is not related to callback methodology.

    1. Sure, callback can be used as a callback to respond to event, just like elem.addEventListener("click", callback);. But not only that.

    A simple example will be illustrated below.

    e.g.

    var map = function(arr, callback) {
      var result = [];
      for (var i = 0, len = arr.length; i < len; i++) {
        result.push(callback(arr[i]));
      }
      return result;
    };
    
    map([0, 1, 2, 3], function(item) {
      return item * 2;
    })
    

    Edited

    This edit is referring to

    For example, if I am making a database call, I do not know how much time it is going to take for the data to be retrieved. If i try to access it before it has arrived, I'll get an error.

    Calling a database, is by no means different from an async http request. So here, I will use XMLHttpRequest to demonstrate how to use callback to ensure this. But normally, these are features provided in browser or node.js already. So you do not need to write it by your own. Of course, to prevent callback hell, I will personally prefer use of Promise or async/await. But this is a bit out of topic.

    So let see how XMLHttpRequest can use callback to handle async task.

    var sendRequest = function(callback) {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
           callback(this); 
        }
      };
      xhttp.open("GET", "filename", true);
      xhttp.send();
    }
    

    and you can use callback to handle async event. Sometime you dont know when it will happen. And the basic idea how it works is from the example I have said in answer 1.

提交回复
热议问题