Created
November 20, 2017 10:43
-
-
Save joseluisq/451bec25be7e6fe040fb3f7b26215bb6 to your computer and use it in GitHub Desktop.
Async/Await Calculator example using `asyncawait` module
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
/** | |
* Async/Await Calculator example | |
* | |
* Tested on Node v6 | |
*/ | |
const _async = require('asyncawait/async') | |
const _await = require('asyncawait/await') | |
const DELAY = 1000 | |
const calculator = () => { | |
const calc = (x) => | |
new Promise((resolve, reject) => { | |
try { | |
setTimeout(() => resolve(x), DELAY) | |
} catch (err) { | |
reject(err) | |
} | |
}) | |
const add = (a, b) => calc(a + b) | |
const subtract = (a, b) => calc(a - b) | |
const multiply = (a, b) => calc(a * b) | |
const divide = (a, b) => calc(a / b) | |
return { | |
add, | |
subtract, | |
multiply, | |
divide | |
} | |
} | |
const add = _async((numbers, b) => { | |
return numbers.map((a) => { | |
console.log(`add: ${a} + ${b}`) | |
const x = _await(calculator().add(a, b)) | |
console.log(`add result: ${x}`) | |
console.log() | |
return x | |
}) | |
}) | |
const multiply = _async((numbers, b) => { | |
return numbers.map((a) => { | |
console.log(`multiply: ${a} x ${b}`) | |
const x = _await(calculator().multiply(a, b)) | |
console.log(`multiply result: ${x}`) | |
console.log() | |
return x | |
}) | |
}) | |
console.log('----- ADD -----') | |
add([ 5, 10, 15, 20, 25 ], 2).then((result) => { | |
console.log('----- ADD RESULTS -----') | |
console.log(result) | |
console.log('----- END ADD -----') | |
console.log() | |
}) | |
console.log('----- MULTIPLY -----') | |
multiply([ 5, 10, 15, 20, 25 ], 2).then((result) => { | |
console.log('----- MULTIPLY RESULTS -----') | |
console.log(result) | |
console.log('----- END MULTIPLY -----') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment