Skip to content

Instantly share code, notes, and snippets.

@terryyounghk
Last active July 31, 2018 08:39
Show Gist options
  • Save terryyounghk/b4ff02837071c2d8ef7612711714a410 to your computer and use it in GitHub Desktop.
Save terryyounghk/b4ff02837071c2d8ef7612711714a410 to your computer and use it in GitHub Desktop.
js hell
// ---------------------------------------------------------------
// 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