[removed] How does a callback function work?

前端 未结 5 869
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 08:16

I\'m really new to JS and I\'m having a lot of trouble writing/understanding callback functions Let\'s say for example, I have the following code, but i dont want



        
5条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 09:05

    Your code dosen't use any asyncronous calls so you wouldent need to use any callbacks to handle the execution. But if you would like to know how to do it, this would be the way.

    numbers = [];   
    greaterThan = []; 
    
    function insertNumbers(callback){
      for (var i = 0; i<11; i++)
      {
        numbers.push(i)
      }
    
      callback(); // now execute the callback funtion
    }
    
    function takeNumbersGreaterThan(number){
    
     for (var m = 0; m number)
          {
             greaterThan.push(numbers[m]);
          }
      }
      console.log(greaterThan);
     }
    
     insertNumbers(function() { // here we send a functions as argument to insertNumbers which will execute when callback() is called
      takeNumbersGreaterThan(5);
    });
    

    insertNumbers takes a argument called "callback". When insertNumbers is finished we simply run callback(). In the initial call to insertNumber we pass a function as argument which will be executed as soon as insertNumers finished (or callback() is called).

提交回复
热议问题