Skip to content

Instantly share code, notes, and snippets.

@niinpatel
Last active June 9, 2018 20:12
Show Gist options
  • Save niinpatel/55de88dee1afb7916d62b3b6ee312dcc to your computer and use it in GitHub Desktop.
Save niinpatel/55de88dee1afb7916d62b3b6ee312dcc to your computer and use it in GitHub Desktop.
Using promises for asynchronous execution.
/*
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