Last active
July 20, 2017 05:54
-
-
Save vgvinay2/4254791580b0770d2627a598875cd05a to your computer and use it in GitHub Desktop.
Callback and Promise
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
1. Array iteration and append its index with the value using callback | |
let IterationArray = function(arr){ | |
let temp = []; | |
arr.forEach(function (value, i) { | |
let my_hash={} | |
my_hash[i] = value | |
temp.push(my_hash); | |
}); | |
return temp; | |
}; | |
let CallIterateArray = function(arr,callback){ | |
return callback(arr); | |
}; | |
console.log(CallIterateArray(["A","B","C","D"],IterationArray)); | |
2. find area and perimeter of the circle using callback | |
let Perimeter = function(radius){ | |
return (2Math.PIradius); | |
}; | |
let Area = function(radius){ | |
return (Math.PIradiusradius); | |
}; | |
let DoWhatever = function(radius){ | |
console.log('here are your radius $(radius)'); | |
}; | |
let CirclePerimeter = function(radius,callback){ | |
return callback(radius); | |
}; | |
console.log(CirclePerimeter(5,Perimeter)); | |
console.log(CirclePerimeter(2,Area)); | |
3. setTimeOut function with callback | |
let TimeOut = function(string){ | |
setTimeout(function(){ alert(string); }, 3000); | |
}; | |
let CallTimeout = function(name,callback){ | |
return callback(name); | |
}; | |
console.log(CallTimeout("Start learning javaScript",TimeOut)); | |
4. find square root of number using promise. | |
function promiseToCalSquareRoot(num) { | |
return new Promise(function (resolve, reject) { | |
let sqt = num*num | |
if (sqt > 0) { | |
resolve(sqt) | |
} else { | |
reject(sqt) | |
} | |
}); | |
}; | |
promiseToCalSquareRoot(3).then(function(result) { | |
console.log('Success: Square Root is ' + result) | |
}).catch(function(error) { | |
console.log('Please enter a number greater than 0 to cal square root: ' + error) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment