Created
September 10, 2018 11:20
-
-
Save prameshbhattarai/f8ccd85ff1ef5167fa7a84094c8c0ea5 to your computer and use it in GitHub Desktop.
example for how javascript callback works .....
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
const users = [ | |
'Jack Howton', | |
'Natividad Claussen', | |
'Jasper Egner', | |
'Adella Troxell', | |
'Edda Methvin', | |
'Aileen Chipley', | |
'Kellee Viles' | |
]; | |
const petNames = { | |
Jack: 'Jackson', | |
Natividad: 'Navi', | |
Jasper: 'Jas', | |
Adella: 'Adele', | |
Edda: 'Ed', | |
Aileen: 'Ail', | |
Kellee: 'Kely' | |
} | |
const getUsers = (callback) => { | |
setTimeout(() => { | |
callback(users); | |
}, 1000); | |
}; | |
const getPetName = (firstName, callback) => { | |
setTimeout(() => { | |
callback(petNames[firstName]); | |
}, 1000); | |
}; | |
const getPetNames = (firstNames, callback) => { | |
setTimeout(() => { | |
const pNames = firstNames.map((firstName) => petNames[firstName]) | |
callback(pNames); | |
}, 1000); | |
}; | |
const getFirstName = (name, callback) => { | |
setTimeout(() => { | |
const firstName = name.split(' ')[0]; | |
callback(firstName); | |
}, 1000); | |
} | |
const getFirstNames = (names, callback) => { | |
setTimeout(() => { | |
const firstNames = names.map((name) => name.split(' ')[0]); | |
callback(firstNames); | |
}) | |
}; | |
const moreThanlength = (name, length) => { | |
return (name.length > length); | |
} | |
// get users | |
getUsers((users) => { | |
// get first names from provided users | |
getFirstNames(users, (firstNames) => { | |
// get pet names from provided first names | |
getPetNames(firstNames, (petNames) => { | |
// get pet names with more than 5 character | |
const petNameMoreThan5Char = petNames.filter((petNames) => moreThanlength(petNames, 4)); | |
console.log(petNameMoreThan5Char); | |
}); | |
}); | |
}); | |
// get users | |
getUsers((users) => { | |
// map each users to get name | |
users.map(name => { | |
// get first name of provided name | |
getFirstName(name, (firstName) => { | |
// get pet name of provided first name | |
getPetName(firstName, (petName) => { | |
console.log(petName); | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment