Last active
June 9, 2018 20:12
-
-
Save niinpatel/72f348c3849225a69c60e4b86f0dadf2 to your computer and use it in GitHub Desktop.
Using Async Await to create asynchronous code.
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
/* | |
An aync function that takes two numbers and performs some operations | |
*/ | |
performOperations(2,3).then(output => console.log(output)).catch(err => console.log(err)); | |
async function performOperations(a,b) { | |
let sum = await addTwoNos(a, b); | |
let doubleOfSum = await double(sum); | |
let squareOfDouble = await square(doubleOfSum); | |
return await double(squareOfDouble); | |
} | |
async function addTwoNos(num1, num2) { | |
if(isNaN(num1) || isNaN(num2)) | |
return await new Error('argument is not a number'); | |
else | |
return await num2 + num1; | |
} | |
async function double(num) { | |
if(isNaN(num)) | |
return await new Error('argument is not a number'); | |
else | |
return await num * 2; | |
} | |
async function square(num) { | |
if(isNaN(num)) | |
return await new Error('argument is not a number'); | |
else | |
return await num * num; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment