Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Callback VS Promise VS async/await
function slowDoubleCallback(x, callback) {
setTimeout(() => {
callback(x * 2);
}, 200);
}
function slowDouble(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(x * 2);
}, 200);
});
}
// Callback Hell Version
let callBackAns = 0;
slowDoubleCallback(1, (ans) => {
callBackAns += ans;
slowDoubleCallback(2, (ans) => {
callBackAns += ans;
slowDoubleCallback(3, (ans) => {
callBackAns += ans;
slowDoubleCallback(4, (ans) => {
callBackAns += ans;
slowDoubleCallback(5, (ans) => {
callBackAns += ans;
slowDoubleCallback(6, (ans) => {
callBackAns += ans;
slowDoubleCallback(7, (ans) => {
callBackAns += ans;
slowDoubleCallback(8, (ans) => {
callBackAns += ans;
slowDoubleCallback(9, (ans) => {
callBackAns += ans;
slowDoubleCallback(10, (ans) => {
callBackAns += ans;
console.log("Callback: " + callBackAns);
});
});
});
});
});
});
});
});
});
});
// Promise Version
let promiseAns = 0;
slowDouble(1).then((ans) => {
promiseAns += ans;
return slowDouble(2);
}).then((ans) => {
promiseAns += ans;
return slowDouble(3);
}).then((ans) => {
promiseAns += ans;
return slowDouble(4);
}).then((ans) => {
promiseAns += ans;
return slowDouble(5);
}).then((ans) => {
promiseAns += ans;
return slowDouble(6);
}).then((ans) => {
promiseAns += ans;
return slowDouble(7);
}).then((ans) => {
promiseAns += ans;
return slowDouble(8);
}).then((ans) => {
promiseAns += ans;
return slowDouble(9);
}).then((ans) => {
promiseAns += ans;
return slowDouble(10);
}).then((ans) => {
console.log("Promise: " + (promiseAns + ans));
});
// async / await Version
(async () => {
let ans = 0;
ans += await slowDouble(1);
ans += await slowDouble(2);
ans += await slowDouble(3);
ans += await slowDouble(4);
ans += await slowDouble(5);
ans += await slowDouble(6);
ans += await slowDouble(7);
ans += await slowDouble(8);
ans += await slowDouble(9);
ans += await slowDouble(10);
console.log("async/await: " + ans);
})();
// async / await Version 2
(async () => {
let ans = 0;
for (let i = 1; i <= 10; i++) {
ans += await slowDouble(i);
}
console.log("async/await Version 2: " + ans);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.