News for hackers. Stuff that matters.

How do promises program flow work in JavaScript?

Promises syntax that I learnt:

    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 in more detail.

( 1 comment | on HN )
Re:How do promises program flow work in JavaScript? by easybake on Monday December 19, 2022 @09:36AM (#34052493)
> My mild guess is when resolve is called .then part happens, and when reject is called .catch part happens.

Yes, calling `resolve` or `reject` will "fulfill" the Promise (that is, the control-flow then returns to the context in which the Promise was invoked.)

Your example is missing an important detail which makes Promises useful. Both `resolve` and `reject` accept an argument which is passed to the callback function (`example.then(handleSuccess)` and `example.catch(handleCatch)`):

  const handlePromise = function(resolve, reject) {
    let x = 20;
    let y = 20;

    // return "Promises will not 'return' a value, they must be resolved or rejected";

    if (x == y) 
      resolve(true);
    
    // reject(false)
    reject(new Error("x != y"))
  }

  const handleSuccess = function(value) {
    console.log(value);
  }

  const handleCatch = function(err) {
    console.error(err);
  }

  const example = new Promise(handlePromise);

  example
    .then(handleSuccess)
    .catch(handleCatch);
> 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.

Context is everything... Promises can be used to `await` asynchronous operations or run synchronous operations in the background. Another use-case is to gracefully handle failed `Fetch` requests (providing notification to the user that a background operation has failed, while also squelching the exception which is thrown during request timeouts, etc...)

> I feel so dumb for asynchronous javascript.

You are in good company.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

[edit: formatting]