'Early return from a subscribe block in a function

I am new to JavaScript. I am trying to do an early return on error from a subscribe block.

This is what I have

public doSomething() {
   this.updateData(data)
     .subscribe((result) => {
                   // do something
                }, 
                (err) => {
                   console.error("Error");
                   return;
                   // require an early return from the block
                   // so rest of the function isn't executed. 
     });
   // do other work
}

Any pointers will be appreciated.



Solution 1:[1]

The best solution would be:

public doSomething() {
   this.updateData(data)
     .subscribe((result) => {
                   // do something
                   // do other work
                }, 
                (err) => {
                   console.error("Error");
                   return;
                   // require an early return from the block
                   // so rest of the function isn't executed. 
     });
}

But you can also use await with async:

public async doSomething() {
       const result = await this.updateData(data);
       if (!result) return;
       // do other things
         
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nir Yossef