xp1632 / DFKI_working_log

0 stars 0 forks source link

Asynchronous Process in JS and 'promise' to achieve that #19

Open xp1632 opened 11 months ago

xp1632 commented 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

image image


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

image


A 6 step process on how to create a promise:

  1. Create the const to contain your promise const CoffeeOrder

  2. Declare a new promise

    const CoffeeOrder = (data) =>  
    new Promise((resolve, reject) => {})
  3. 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';
    })
  4. ‘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);
    })
  5. Use the promise however you want by calling it 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);
    })