Skip to content

Instantly share code, notes, and snippets.

@vgvinay2
Last active July 20, 2017 05:54
Show Gist options
  • Save vgvinay2/4254791580b0770d2627a598875cd05a to your computer and use it in GitHub Desktop.
Save vgvinay2/4254791580b0770d2627a598875cd05a to your computer and use it in GitHub Desktop.
Callback and Promise
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