Last active
August 29, 2015 14:08
-
-
Save JacobHsu/93d269205cadd24934d2 to your computer and use it in GitHub Desktop.
#JS What is callbacks?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function basic( callback ){ | |
console.log( '作些事情' ); | |
var result = '我是等會要被傳送給 `do something` 的 callback 的函式結果'; | |
// 如果 callback 存在的話就執行他 | |
callback( result ); | |
} | |
basic( function( result ){ | |
console.log( '這個 callback 函式會在 terminal 上列出 `basic` 函式執行的結果' ); | |
console.log( result ); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function do_a( callback ){ | |
setTimeout( function(){ | |
// 模擬一個需要長間的 function | |
console.log( '`do_a`: 這個需要的時間比 `do_b` 長' ); | |
// 如果 callback 存在的話就執行他 | |
callback && callback(); | |
}, 3000 ); | |
} | |
function do_b(){ | |
console.log( '`do_b`: 現在我們就可以肯定 `do_b` 出現在 `do_a` 之後了' ); | |
} | |
do_a( function(){ | |
do_b(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment