- 取得連結
- X
- 以電子郵件傳送
- 其他應用程式
Javascript麻瓜:callback 是什麼?
For Javascript Muggle: What is callback
Simply put: A callback is a function that is to be executed after another function has finished executing — hence the name ‘call back’.
More complexly put: In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions. Functions that do this are called higher-order functions. Any function that is passed as an argument is called a callback function.
Example 1,
- function sayHello()
- {
- console.log('Hello everyone');
- }
- setTimeout(sayHello(), 3000)
function sayHello() is a function and it is passed as an argument of the function setTimeout, i.e. the function setTimeout takes the fucntion sayHello() as its argument. setTimeout is called a higher-order function. sayHello() is called a callback function. The callback function sayHello() is executed after 3000 miliseconds is past.
Callbacks are primarily used while handling asynchronous operations like – making an API request, fetching/writing some data from/into a file, registering event listeners and related stuff. All the operations mentioned uses callbacks. This way once the data/error from the asynchronous operation is returned, the callbacks are used to do something with that inside our code.
Always place the callback function as the last argument of the function. This has the name called callback pattern.I In this way, our code will be more readable and will be maintained more easily when other programmers work on it.
Example 2,
- var funcA = function()
- {
- console.log('function A');
- };
- var funcB = function(){
- console.log('function B');
- };
- funcA();
- funcB();
The output will be like this:
"function A""function B"
However, if we change the codes and generate the waiting time by random way, there is likely funcB will be executed prior to funcA. How could we guarantee the funcA will still be executed prior to funcB? We can apply callback.
Example 3,
- var funcA = function(cb)
- {
- var i = Math.random() + 1; //generate random number plus 1 to make sure i will not be 0
- window.setTimeout(function() {
- console.log('function A');}, i * 1000);
- if (typeof cb==='function') {cb();}
- };
- var funcB = function() //will be passed as an argument of funcA, i.e. a callback function of function funcA.
- {
- var i = Math.random() + 1;
- window.setTimeout(function() {console.log('function B');}, i * 1000);
- };
- funcA(funcB);
This way will ensure the funcA to be executed and finished before funcB.
Example 4,
- function callbackSleepWorker() {
- alert('OK, Im wake up !')
- }
- function ICallYouWhenIDone(cb) {
- alert('OK, Im first.')
- cb()
- }
- ICallYouWhenIDone(callbackSleepWorker)
In this example function ICallYouWhenIDone(callbackSleepWorker), we have two workers. Worker A will firstly send the alert saying 'OK, I'm first'. When he gets his work done, he will immediately call worker B to get started working. When worker B starts working, he send alert saying 'OK, Im wake up!'
Example 5,
- let money = null
- function slower() {
- setTimeout(function() {
- money = 30
- }, 200)
- }
- function faster() {
- setTimeout(function() {
- console.log('I have ' + money)
- }, 100)
- }
- slower();
- faster();
The output will be 'I have null' because javascript will execute firstly the function that takes shorter time to complete. However, if we rewrite the codes as Example 6, the output will be 'I have 30'
Example 6,
- let money = null;
- function slower(cb) {
- setTimeout(function() {
- money = 30;
- cb();
- }, 200)
- };
- function faster() {
- setTimeout(function() {
- console.log('I have ' + money);
- }, 100)
- };
- slower(faster);
Example 7,
- // add() function is called with arguments a, b
- // and callback, callback will be executed just
- // after ending of add() function
- function add(a, b , disp)
- {
- sum=a+b;
- console.log(`The sum of '+a+' ' +'and '+b+' '+'is '+sum);
- disp();
- } ;
- // printSum() function is called just
- // after the ending of add() function
- function printSum(){console.log('This must be printed after addition'); } ;
- // Calling add() function
- add(5,6,printSum);
The output will be
- 'The sum of 5 and 6 is 11.
- This must be printed after addition'
Example 8,
- T.get('search/tweets', params, function(err, data, response) {
- if(!err){
- console.log('This is where the magic will happen');
- }
- else {
- console.log(err);
- }
- })
- T.get() simply means we are making a get request to Twitter
- There are three parameters in this request: ‘search/tweets’, which is the route of our request, params which are our search parameters, and then an anonymous function which is our callback.
A callback is important here because we need to wait for a response from the server before we can move forward in our code. We don’t know if our API request is going to be successful or not so after sending our parameters to search/tweets via a get request, we wait. Once Twitter responds, our callback function is invoked. Twitter will either send an err (error) object or a response object back to us. In our callback function we can use an if() statement to determine if our request was successful or not, and then act upon the new data accordingly.
- 取得連結
- X
- 以電子郵件傳送
- 其他應用程式
留言