Skip to content

Instantly share code, notes, and snippets.

@arol
Created December 1, 2017 15:31
Show Gist options
  • Save arol/7f9b5781da2ef7180d173f88343a7e08 to your computer and use it in GitHub Desktop.
Save arol/7f9b5781da2ef7180d173f88343a7e08 to your computer and use it in GitHub Desktop.
const randomNumber = () => {
return Math.random();
}
// 1. Make it wait for 1 sec. with `setTimeout`
const timeoutRandomNumber = (cb) => {
setTimeout(() => {
cb(null, randomNumber())
}, 1000);
}
// 2. Now wrap the timeout version to work with promises
const promiseRandomNumber = () => {
return new Promise((resolve, reject) => {
timeoutRandomNumber((err, rnd) => {
if (err) reject(err);
else resolve(rnd);
})
});
}
// 3. Finally, code a final version with async await.
const asyncRandomNumber = async () => {
// Just a clarification, this is quite absurd and we're doing it only for
// learning purposes. Returning the await of another function in an async
// function (with no other awaits) it's useless. Simply return the execution
// of `promiseRandomNumber`, which already returns a promise.
return await promiseRandomNumber();
}
const rangedRandomNumber = (base, min, max) => {
return Math.floor((base*(max-min))+min);
}
const main = async () => {
// 0. Without asynchronicity
const rnd = randomNumber()
console.log('Not asynchronous', rangedRandomNumber(rnd, 14, 42));
// 1. Callbacks
timeoutRandomNumber((err, rnd) => {
if(err) {
// return in here is only for halting
return console.error(err);
}
console.log('Callback', rangedRandomNumber(rnd, 14, 42));
})
// 2. Promises
promiseRandomNumber()
.then(rnd => {
console.log('Promise', rangedRandomNumber(rnd, 14, 42));
})
.catch(e => {
console.error(e);
})
// 4. async/await (wee need to prefix main with async. See line 31)
const number = await asyncRandomNumber();
console.log('async/await', rangedRandomNumber(number, 14, 42));
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment