How do promises program flow work?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • shivajikobardan
    New Member
    • Jun 2022
    • 12

    How do promises program flow work?

    Promises syntax that I learnt:


    Code:
    let p = new Promise(function (resolve, reject) {
      let x = 20, y = 20;
      if (x == y) {
        resolve();
    
      }
      else {
        reject();
      }
    })
    
    p.then(function () {
      console.log("that's correct");
    })
    
      .catch(function () {
        console.log("that's not correct");
      })
    I don't even understand what happens here, the flow control of here. My mild guess is when resolve is called .then part happens, and when reject is called .catch part happens.


    I've like read countless articles, banged my head against the wall but it's still not getting inside my head. I feel so dumb for asynchronous javascript.

    Please help me understand the program flow step by step.
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    then() is called, when the promise gets fulfilled (resolved or rejected), i.e. the callback does not throw an error. The difference between resolve() and reject() is that resolve() will trigger the first callback in then() and reject() will trigger the second callback (if one was defined).

    Any errors you throw inside a callback will trigger the callback in catch().

    The then() method of Promise instances takes up to two arguments: callback functions for the fulfilled and rejected cases of the Promise. It stores the callbacks within the promise it is called on and immediately returns another Promise object, allowing you to chain calls to other promise methods.

    The catch() method of Promise instances schedules a function to be called when the promise is rejected. It immediately returns another Promise object, allowing you to chain calls to other promise methods. It is a shortcut for then(undefined, onRejected).

    Comment

    Working...