Last active
June 9, 2018 20:12
-
-
Save niinpatel/55de88dee1afb7916d62b3b6ee312dcc to your computer and use it in GitHub Desktop.
Using promises for asynchronous execution.
This file contains hidden or 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
/* | |
Suppose I want to add two numbers, then double it, then square that number, then add double it again. Using Promises. | |
*/ | |
addTwoNos(2, 3) | |
.then(sum => double(sum)) | |
.then(doubleOfSum => square(doubleOfSum)) | |
.then(square => double(square)) | |
.then(output => console.log(output)) | |
.catch(err => console.log(err)); | |
function addTwoNos(num1, num2) { | |
return new Promise((resolve, reject) => { | |
if(isNaN(num1) || isNaN(num2)){ | |
reject(new Error('argument is not a number') ) | |
} | |
else { | |
resolve(num1 + num2) | |
} | |
}) | |
} | |
function double(num) { | |
return new Promise((resolve, reject) => { | |
if(isNaN(num)){ | |
reject(new Error('argument is not a number') ) | |
} | |
else { | |
resolve(num * 2) | |
} | |
}) | |
} | |
function square(num) { | |
return new Promise((resolve, reject) => { | |
if(isNaN(num)){ | |
reject(new Error('argument is not a number') ) | |
} | |
else { | |
resolve(num * num) | |
} | |
}) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment