Last active
July 31, 2018 08:39
-
-
Save terryyounghk/b4ff02837071c2d8ef7612711714a410 to your computer and use it in GitHub Desktop.
js hell
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
// --------------------------------------------------------------- | |
// Callback Hell | |
moveTo(50, 50, function () { | |
moveTo(20, 100, function () { | |
moveTo(100, 200, function () { | |
// done | |
}); | |
}); | |
}); | |
// The actual 'moveTo' function for "Callback Hell" | |
function moveTo (x, y, callback) { | |
// do something with x and y | |
callback(); | |
} | |
// --------------------------------------------------------------- | |
// Promise hell | |
moveTo(50, 50) | |
.then(function () { | |
moveTo(20, 100); | |
}) | |
.then(function () { | |
moveTo(100, 200); | |
}); | |
// or, using the new shorthand way of writing functions... | |
moveTo(50, 50) | |
.then(() => moveTo(20, 100)) | |
.then(() => moveTo(100, 200)); | |
// The actual 'moveTo' function for "Promise Hell" | |
function moveTo (x, y) { | |
return new Promise(function (resolve, reject) { | |
// do something with x and y | |
resolve(); | |
}); | |
} | |
// --------------------------------------------------------------- | |
// Async/Await hell | |
async function animate() { | |
await moveTo(50, 50); | |
await moveTo(20, 100); | |
await moveTo(100, 200); | |
} | |
// The actual 'moveTo' function for Async/Await should return a new Promise | |
function moveTo (x, y) { | |
return new Promise(function (resolve, reject) { | |
// do something with x and y | |
resolve(); | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment