At the very beginning when I started watching Js code on line I was totally confused by all these terms, now it’s better, but I have not got used to async/await…
setTimeout function to simulate the web transfer delay, and firstly create an array to play with.
const pokemons = [
{name:'Pikachu', ability:'Lighteningrod'},
{name:'Psyduck', ability:'Damp'}
]
Callback
I think it is a way to chain functions, arrange them to act with order.
If getPokemons needs 1 second, createPokemon need 2 second, due to the timeframe, only the two pokemons are printed on console
const getPokemons = () => {
setTimeout(()=>{
console.log(pokemons)
},1000)
}const creatPokemons = (pokemon) => {
setTimeout(()=>{
pokemons.push(pokemon)
},2000)
}creatPokemons({name:'Squitle', ability:'torrent'})
getPokemons()
We can use callback to arrange the order, callback() is simply a placeholder
const creatPokemons = (pokemon, callback) => {
setTimeout(()=>{
pokemons.push(pokemon)
callback()
},2000)
}creatPokemons({name:'Squitle', ability:'torrent'},getPokemons)
Promises
several callbacks can cause miserable nested functions which is really hard to read, promises can make it neat.
It’s actually a wrapper of your callback function, itself is a callback function
const creatPokemons = (pokemon) => {
return new Promise((resovle,reject)=>{
setTimeout(()=>{
pokemons.push(pokemon)
let error = false
if(!error){
resovle()}
else {
reject('a error is throw to your face')
}
},2000)
})}result = creatPokemons({name:'Squitle', ability:'torrent'})
.then(getPokemons)
.catch(err=>console.log(err))
// console.log(result)
Async/Await
Take a step further to make handling async promises codes looks like sync codes
const result = async func(){
await creatPokemons({name:'Squitle', ability:'torrent'})
getPokemons()
}result()
Learning Materials
Traversy Media, his voice is always clam