首页 > 解决方案 > Reject JavaScript promise

问题描述

I am building an Angular application where I have a service for selecting items from a canvas. Once the user clicks a button that allows him to start selecting I also show a snackbar which informs the user that he is in selecting mode and he can start selecting. The snackbar has a cancel button that can stop the selecting mode. The problem is that the selection service returns a Promise that I have to reject if the user cancels the selecting mode from the snackbar. The code:

public startSelecting() {
  this.showSnackbar();
  
  // I wait for the user to select something
  this.selectionService.getSelection().then(selection => {
    // If the user selects an item I can close the snackbar
    this.snackbarService.close();

    // do something with the selection
  });
}

private showSnackbar() {
  this.snackbarService.show().subscribe(close => {
    // This is an observable that emits if the users cancels the snackbar,
    // therefore the selecting mode. Here I want to cancel the Promise from above
  });
}

Thanks in advance for any help!

标签: javascriptangularpromise

解决方案


推荐阅读