Created
March 28, 2018 13:01
-
-
Save kuanhsuh/7a336abbcdc16fdb9545ede5e3b70026 to your computer and use it in GitHub Desktop.
callback vs promises
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
function logWord(word){ | |
setTimeout(function() { | |
console.log(word) | |
}, Math.floor(Math.random() * 100) + 1 | |
// return value between 1 ~ 100 | |
) | |
} | |
function logAll(){ | |
logWord("A") | |
logWord("B") | |
logWord("C") | |
} | |
logAll() | |
// Callbacks | |
function logWord(word, callback) { | |
setTimeout(function() { | |
console.log(word) | |
callback() | |
}), Math.floor(Math.random() * 100) + 1 | |
} | |
function logAll(){ | |
logWord("A", function() { | |
logWord("B", function() { | |
logWord("C", function() {}) | |
}) | |
}) | |
} | |
// Callback Hell | |
logAll() | |
// Promises | |
function logWord(word) { | |
return new Promise(function (resolve, reject) { | |
setTimeout(function() { | |
console.log(word) | |
resolve() | |
}, Math.floor(Math.random() * 100) + 1) | |
}) | |
} | |
function logAll() { | |
logWord('A') | |
.then(function() { | |
return logWord('B') | |
}) | |
.then(function() { | |
return logWord('C') | |
}) | |
} | |
logAll() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment