Callbacks, Promises & Async - marcoFijan/projectTech GitHub Wiki
Callbacks
With Callbacks you can give a function as a parameter. The function doesn't need to be declared in the parameter. AddeventListener is an example of callbacks where you first declare the action that must happen before you run the function. For example 'click':
addEventListner('click', aFunction(4, 5))
function(x, y){
return x + y;
}
Callbacks are higher order functions cause you call a function inside a function
Promises
A promise has 3 states:
- Pending (waiting / default state) (Example: You make an appointment to a restaurant)
- Fulfilled (When your promise is ready / your received something) (Example: You're getting called by the restaurant)
- Rejected (When something goes wrong) (Example: You're getting called, but you get the news you can't come to the restaurant)
You write a new promise like this:
const promise = new Promise((resolve, reject) => {
setTimeout() => {
resolve()
}
promise.then(onSucces)
promise.catch(onFailure)
})
Why promises? You can chain them!
function myPromise() {
return new Promise((resolve, reject) => {
setTimeout() => {
resolve()
}
}
}
myPromise()
.then(doThis)
.then(thenDoThis)
.then(doThatThing)
.catch(logErr)
Lastly, Async-Await
async function getMehData() { //SET ASYNC
const userData = await getUserData(); //USE THIS FUNCTION LIKE A PROMISE
const weather = await getCurrentWeather(); //USE THIS FUNCTION LIKE A PROMISE
return {
user: userData,
degrees: weather.currentDegrees
}
}
You can also run the promises paralel:
const data = Promises.all([userData, weather])