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.

Recommended Answers

All 2 Replies

A promise object consists of a block of code, as well as a name for a callback function if the block of code is successful, and a name for a callback function if the block of code is a failure.

Here, you're creating a new promise in which the constructor function (that's used to create the object) of the object is an anonymous function which takes two arguments: you pass in the function name you will be using for the success callback (resolve), and the function name you will be using the failure callback (reject).

The block of code in the anonymous function then has a conditional statement that determines if the promise is successful or not.

In your then-catch block, then handles what happens when resolve() is called and catch handles what happens when reject() is called. So, as it would seem, your assumption is correct. Good luck!

I think you meant to do something like this

// first write your function that return a promise
function isCorrect (x,y) {
  return new Promise(function (resolve, reject) {
    if(x===20 && y===20){
      resolve(`your numbers are good`);
    }else{
      reject(`your numbers are wrong`);
    }
  });
}

// then you can call your function
isCorrect(20,20).then(result=>{
    console.log(result);
}).catch(error=>{
    console.log(error);
})
// code above will print: your numbers are good


// you can write the function with typescript to better understand it
// we can see that x,y arguments suppose to be numbers
// we can see that the function return a string promise
function isCorrectTyped (x: number,y: number):Promise<string> {
  return new Promise(function (resolve, reject) {
    if(x===20 && y===20){
      resolve(`your numbers are good`);
    }else{
      reject(`your numbers are wrong`);
    }
  });
}

// you can also write the function using arrow syntax
const isCorrectArrow = (x,y)=>{
  return new Promise(function (resolve, reject) {
    if(x===20 && y===20){
      resolve(`your numbers are good`);
    }else{
      reject(`your numbers are wrong`);
    }
  });
}

// or arrow with type checking
const isCorrectArrowTyped = (x: number,y: number):Promise<string>=>{
  return new Promise(function (resolve, reject) {
    if(x===20 && y===20){
      resolve(`your numbers are good`);
    }else{
      reject(`your numbers are wrong`);
    }
  });
}

// you can call all the functions above like the example in the beginning
isCorrectArrowTyped(10,20).then(result=>{
    console.log(result);
}).catch(error=>{
    console.log(error);
})
// code above will print: your numbers are wrong


// but in your example you can just type a normal function
// no need to use a promise that check the numbers
// function like this will be good
function isCorrect(x,y){
    if(x===20 && y===20) return `your numbers are good`;
    return `your numbers are wrong`;
}

// call the function above like so
isCorrect(20,20);
// will print your numbers are good


// usually we use promises / async / await with non blocking events
// like so
function isCorrectWithTimeout (x,y) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      if(x===20 && y===20){
        resolve(`your numbers are good`);
      }else{
        reject(`your numbers are wrong`);
      }
    }, 5000);
  });
}

// call the function above
isCorrectWithTimeout(20,20).then(result=>{
    // 5 sec to get the answer
    console.log(result);
}).catch(error=>{
    // 5 sec to get the answer
    console.log(error);
})
// code above will print: your numbers are good (after 5 sec)

// usually we use promises for ajax calls, reading wrting files, database connections etc...
// we can also use the newer async await syntax
// if you want to know more about async await write down and i will explain
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.