DEV Community

amythical
amythical

Posted on

My mistake with resolve and return resolve

TLDR : Just calling resolve does not stop further code execution, return resolve is the right way to stop further code execution.

Lets see this example.

function fun1(){
  returns new Promise(){
      console.log("Before calling fun2");
      fun2().then(response){
          if(response == 1234){
             resolve(response);
          }
          console.log("After resolve");
      }
  }
}
Enter fullscreen mode Exit fullscreen mode

Now if you run this, the console prints

Before calling fun2
After resolve
Enter fullscreen mode Exit fullscreen mode

But ... I had called resolve so the code at "After resolve" should not have been reached.
WRONG!

Correct use

fun2().then(response){
          if(response == 1234){
             return resolve(response);
          }
          console.log("After resolve");
      }
Enter fullscreen mode Exit fullscreen mode

Now it works as expected and returns where intended stopping further code execution.

This was a small oversight but it leads to unexpected behaviour in the logic flow if ignored.

Just sharing my experiences, small things that will save time, sweat and hair on the head.

Cheers.

Top comments (0)