Open xp1632 opened 11 months ago
This is a good video(12:34)about callback function and asynchronous Process, I didn't watch it yet: https://www.youtube.com/watch?v=r_MeovK0-Ps
And now, because javascript is synchronous and top to bottom, to achieve async actions, we use promises, and here's a simple illustration of promise: https://medium.matcha.fyi/promises-promises-promises-5ae43c26bb8d
A 6 step process on how to create a promise:
Create the const to contain your promise const CoffeeOrder
const CoffeeOrder
Declare a new promise
const CoffeeOrder = (data) => new Promise((resolve, reject) => {})
Write whatever code you need to write.
const CoffeeOrder = (data) => new Promise((resolve, reject) => { console.log('2 + 2 - 1 = 3 Quick maths'); //some more code here. let returnedValue = 'order completed'; })
‘Resolve' the promise to complete the process or ‘Reject' to abort the promise and tell the caller that something went wrong.
const CoffeeOrder = (data) => new Promise((resolve, reject) => { console.log('2 + 2 - 1 = 3 Quick maths'); //some more code here. let returnedValue = 'order completed'; resolve(returnedValue); })
Use the promise however you want by calling it CoffeeOrder(coffeeData)
CoffeeOrder(coffeeData)
6 . 'then()' at the end of the call to capture the end results.
CoffeeOrder(coffeeData) .then(res => { console.log(res); //console will log 'order completed' })
Bonus step: what if you want to chain several promises together? Return the promise function and put on another then() at the end like this:
//calling the CoffeeOrder promise twice CoffeeOrder(coffeeData) .then(res => { return CoffeeOrder(res); }).then(res => { console.log(res); })
This is a good video(12:34)about callback function and asynchronous Process, I didn't watch it yet: https://www.youtube.com/watch?v=r_MeovK0-Ps
And now, because javascript is synchronous and top to bottom, to achieve async actions, we use promises, and here's a simple illustration of promise: https://medium.matcha.fyi/promises-promises-promises-5ae43c26bb8d
A 6 step process on how to create a promise:
Create the const to contain your promise
const CoffeeOrder
Declare a new promise
Write whatever code you need to write.
‘Resolve' the promise to complete the process or ‘Reject' to abort the promise and tell the caller that something went wrong.
Use the promise however you want by calling it
CoffeeOrder(coffeeData)
6 . 'then()' at the end of the call to capture the end results.
Bonus step: what if you want to chain several promises together? Return the promise function and put on another then() at the end like this: