Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
/* ------ section 1: callback-based code for native methods ------ */
// Callback are functions passed as parameters that can be called later.
function nativeMethodWithCallback(callback) {
console.log("API method called, execution done, about to callback");
function callbackMethodToBeExectuedLater() {
console.log("Logged later when the api method is done.");
// example 1
//example 2
// You can, and often do, use anonymous functions as callbacks.
nativeMethodWithCallback(() => {
console.log("I'm an anonymous callback function.");
/* ------ section 2: callback-based code for APIs provided by the browser ------ */
// This example shows callbacks with setTimeout
function setTimeoutMethodWithCallback(callback) {
console.log("setTimeoutWithCallback called, going to start a timeout queue the callback");
setTimeout(callback, 1500);
console.log("This will run while we're waiting for our setTimeout queued callback, because setTimeout doesn't block.");
setTimeoutMethodWithCallback(() => {
console.log("Hey, I'm the callback that was queued after the setTimeout finished executing.");
/* ------ section 3: callback-based code for external APIs ------ */
// the callback here is invoked after the asynchronous work is completed to download the bytes from the URL provided
function fetchSomeDataAndCallback(callback) {
console.log("About to fetch data.");
var xhr = new XMLHttpRequest();"GET", "", true);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.onload = callback;
fetchSomeDataAndCallback((data) => {
console.log("fetch returned", data);
/* ------------------------------------------------------------------- */
// Callbacks are ugly, especially when chained together.
// Promises were invented to make the flow of control through callback-based code more obvious.
// Let's wrap our XHR request in a promise as an example.
/* ------------------------------------------------------------------- */
/* ------ section 4: promise based code for external APIs with .then ------ */
function fetchSomeDataAndReturnPromise() {
console.log("About to fetch data and return promise.");
// Our promise here wraps the callback-based code
// We use the "resolve" function - itself a callback provided by the Promise constructor
// and when our data is ready, we call it.
// Promises allow us to return early, before the out of process / long running work is done
// and act on data by "chaining" the promises' "then" methods.
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();"GET", "", true);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.onload = (data) => {
fetchSomeDataAndReturnPromise().then((data) => {
console.log("I got promised data!", data);
/* ------------------------------------------------------------------- */
/*Promises look better than callbacks in the consuming code because you don't end up
with lots of nested functions. However, the chains of "then then then" are often visually distracting.
This led to the async/await syntax being added to the language to tidy up some of the syntactic noise.
async/await is just "syntactic sugar" - the code that you use async/await with is still
really just promises, but the language provides a more pleasant way to interact with them.
// Let's use the exact same fetchSomeDataAndReturnPromise function with async/await
/* ------------------------------------------------------------------- */
/* ------ section 5: promise based code for external APIs with async/await ------ */
(async () => {
const data = await fetchSomeDataAndReturnPromise();
console.log("I got awaited data here", data);
/* Most of the browsers WebAPIs and node.js's APIs are being switched to use Promises instead
of passing callbacks to functions now, and anywhere where promises appear, you can use async/await.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment