Created
March 22, 2019 21:19
-
-
Save gbroques/5466d638f2e6acab7a106b11c208c7a5 to your computer and use it in GitHub Desktop.
Asynchronous Sum Example with Callbacks, Promises, and Async / Await
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
/** | |
* Asynchronous sum example with callbacks. | |
*/ | |
function getX(callback) { | |
setTimeout(() => { | |
callback(5); | |
}, 1000); | |
} | |
function getY(callback) { | |
setTimeout(() => { | |
callback(3); | |
}, 2000); | |
} | |
function asyncSum(callback) { | |
let x, y; | |
getX(result => { | |
x = result; | |
if (y !== undefined) { | |
callback(x + y); | |
} | |
}); | |
getY(result => { | |
y = result; | |
if (x !== undefined) { | |
callback(x + y); | |
} | |
}) | |
} | |
console.log("Loading..."); | |
asyncSum(sum => console.log("sum", sum)); | |
// =================================================== | |
/** | |
* Asynchronous sum example with promises. | |
*/ | |
function getX() { | |
return new Promise(resolve => { | |
setTimeout(() => resolve(5), 1000); | |
}); | |
} | |
function getY() { | |
return new Promise(resolve => { | |
setTimeout(() => resolve(3), 2000); | |
}); | |
} | |
function asyncSum() { | |
return new Promise(resolve => { | |
const xPromise = getX(); | |
const yPromise = getY(); | |
Promise.all([xPromise, yPromise]).then(([x, y]) => { | |
resolve(x + y); | |
}); | |
}) | |
} | |
console.log("Loading..."); | |
asyncSum().then(sum => { | |
console.log("sum", sum); | |
}); | |
// =================================================== | |
/** | |
* Asynchronous sum example with async / await. | |
*/ | |
function getX() { | |
return new Promise(resolve => { | |
setTimeout(() => resolve(5), 1000); | |
}); | |
} | |
function getY() { | |
return new Promise(resolve => { | |
setTimeout(() => resolve(3), 2000); | |
}); | |
} | |
async function asyncSum() { | |
const xPromise = getX(); | |
const yPromise = getY(); | |
const x = await xPromise; | |
const y = await yPromise; | |
return x + y; | |
} | |
async function printSum() { | |
const sum = await asyncSum(getX, getY); | |
console.log("sum", sum); | |
} | |
console.log("Loading sum..."); | |
printSum(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment