Created
January 5, 2017 06:09
-
-
Save bepitulaz/efde245ae96fba602a351fc5fa8ddc80 to your computer and use it in GitHub Desktop.
Callback vs Promise
This file contains hidden or 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
| /** | |
| MASALAH: | |
| Anggap kita punya 3 asynchronous function yang harus dijalankan berurutan. | |
| Jadilah callback hell seperti di bawah ini. | |
| Apalagi jika kita harus menjalankan operasi tertentu di antara | |
| callback-callback tersebut yang membuat kode menjadi panjang, dan tentunya | |
| makin sulit dibaca. | |
| */ | |
| jQuery.get('http://example.com/data.json', function(response) { | |
| // lakukan sesuatu dengan `response` dari operasi 1 | |
| jQuery.get('http://example.com/data-2.json', function(response) { | |
| // lakukan sesuatu dengan `response` dari operasi 2 | |
| jQuery.get('http://example.com/data-3.json', function(response) { | |
| // lakukan sesuatu dengan `response` dari operasi 3 | |
| }); | |
| }) | |
| }); | |
| /** | |
| SOLUSI: | |
| Gunakan function yang diberi nama daripada menggunakan anonymous function | |
| seperti di atas. | |
| */ | |
| jQuery.get('http://example.com/data.json', afterFirstOps); | |
| function afterFirstOps(response) { | |
| // lakukan sesuatu dengan `response` dari operasi 1 | |
| jQuery.get('http://example.com/data-2.json', afterSecondOps); | |
| } | |
| function afterSecondOps(response) { | |
| // lakukan sesuatu dengan `response` dari operasi 2 | |
| jQuery.get('http://example.com/data-3.json', afterThirdOps); | |
| } | |
| function afterThirdOps(response) { | |
| // lakukan sesuatu dengan `response` dari operasi 3 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment