Promise has been unfulfilled

Currently adding this button to my application.

In the button component, the following code is present:

  @Input() callback: () => Promise<null>;
  onClick() {
    this.spinnerService.show();
    this.callback().then(() => {
      this.spinnerService.hide();
    }, () => {
      this.spinnerService.hide();
    });
  }

(Avoiding async / await as per the directive given by the "tech lead")

The template for the component:

<my-button [callback]="doSomething">
</my-button>

Everything seems to be functioning well when passing the mentioned code to the input of the component:

doSomething = () => {
  return myService.doSomething()
    .toPromise()
    .then((response) => console.log('promise resolved'));
}

However, there is a need to exit from this function prematurely:

doSomething() {
  if (condition) {
    return;
  }
  return myService.doSomething()
    .toPromise()
    .then((response) => console.log('promise resolved'));
}

An error is encountered:

ERROR TypeError: Cannot read property 'then' of undefined

Attempts were made to create and force a promise with similar outcomes:

  if (condition) {
    return Promise.resolve(null);
    // or
    return new Promise((resolve) => { resolve(null); });
  }

Answer №1

When dealing with the following input:

@Input() callback: () => Promise<null>;

there is no guarantee that it's assigned to a proper value. It is recommended to add an additional check to verify if callback was specified.

An alternative and safer approach is to utilize async functions in these scenarios as they consistently handle promises:

  async onClick() {
    this.spinnerService.show();

    try {
      if (this.callback)
        await this.callback()
    } finally {
      this.spinnerService.hide();
    }
  }

The function doSomething should unconditionally return a promise, which can be achieved using async:

async doSomething() {
  if (!condition)
    return myService.doSomething().toPromise();
}

If you are unable to use async functions for any reason, it is crucial to consistently process promises within functions. Also, ensure that doSomething is properly typed to avoid improper function return:

  onClick(): Promise<void> {
    this.spinnerService.show();

    return Promise.resolve(this.callback ? this.callback() : undefined)
    .catch(() => {})
    .then(() => {
      this.spinnerService.hide();
    });
  }

Additionally,

doSomething(): Promise<void> {
  if (condition) {
    return Promise.resolve();
  }

  return myService.doSomething().toPromise();
}

Ensure that the type of callback is Promise<void>, not Promise<null>.

Lastly, the regular (non-arrow) doSomething method should be bound to this in the constructor.

Answer №2

give this a shot

executeAction() {
  if (condition) {
    return new Promise((resolve,reject)=> reject('An Error Occurred'));
  }
  return myService.performAction()
    .toPromise()
    .then((response) => console.log('promise fulfilled'));
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Three.js effect is functional on Firefox but experiencing issues on Chrome

I have recently implemented a recursive search for adjacent faces using a Half Edge data structure and I am facing an issue where the effect is visible on Firefox but not on Chrome. I am seeking assistance in resolving this problem. Any help or suggestions ...

Ways to activate an event based on the dimensions (width/height) of

Exploring ways to implement an if statement based on specific width/height values using this code example. Check out the code snippet here My approach: <p id="confirmation">Try again!</p> <script> if (new dynamicSize.width() < ...

The panup and pandown events in Ionic 2 seem to be malfunctioning

In my Ionic 2 project, I am currently working on implementing a drag and drop feature. To achieve this, I have utilized the following event in Ionic 2: <div (press) = "onDragInit(item, $event)" (panstart)="dragStart($event)" (panup)="onDra ...

Is it possible to utilize async and await functions to update an object and then insert it into an

We are currently facing some challenges with promises while utilizing the async and await keywords to retrieve counts from another function. Although we understand that using then() can resolve this issue, we need a method to update the outer array/object ...

Is there a way to make the ExecuteQueryAsync method behave in a more synchronous manner?

Okay, so I'm using JavaScript in SharePoint and relying on Alerts to debug my script that runs from a Content Editor Web Part located in the Assets library. I understand that "async" function calls are meant to not wait around for the call to finish, ...

Issues with previewing PDF files in AngularJS

I am trying to display a PDF preview on my website using the following code: var $scope; angular.module('miniapp', ['phonecatFilters', 'ngSanitize']); function Ctrl($scope) { $scope.test = 'Example from: '; ...

I am encountering difficulties importing the React-hexgrid library

Although I have verified that the library path is correct, I am still encountering an error. Here is the code snippet: "react-hexgrid": "2.0.1", "react": "18.2.0" "next": "13.4.3" Click here to v ...

Updating Angular libraries can enhance the performance and functionality of

Within our organization, we rely on several custom Angular libraries for the majority of our projects. The issue arises when we need to update our codebase to a new version of Angular, as it requires updating all libraries simply to ensure compatibility ...

What is the best way to enable onClick events for individual elements within a .map() function?

I am currently building a chat application and need to display a list of users in the chat. Each user should have a button that, when clicked, opens a menu allowing admins to ban that specific user. However, I am facing an issue where clicking on the &apos ...

Using PHP associative arrays as null values in JavaScript functions

On my PHP webpage, I have 6 textboxes arranged like this: <html> <script type="text/javascript"> function add() { //Issue with PHP associative array not transferring to JS array var array = JSON.par ...

Best practices for bundling ambient module in typescript for npm distribution

Imagine creating an npm package named get-subject with a source file called src/index.ts. This is how the code looks: import { ReplaySubject } from 'rx'; export default function getSubject() { return new ReplaySubject(1); } The package inclu ...

Executing a complex TypeORM query using a chain of promises

Currently, I am retrieving data from various tables in typeorm using the following method: Order.findOne(orderId).then(order => { Stuff.findOne(order?.stuffId).then(stuff => { Site.findOne(stuff?.storeId).then(store => { Stuff.findOne ...

Maintain the functionality of an object even when it is created using the "bind" method

I'm working with a function that has the following structure: var tempFun = function() { return 'something'; } tempFun.priority = 100; My goal is to store this function in an array and bind another object to it simultaneously, like so ...

Utilizing Angular's resolve feature for data bindings within views

Is there a way to pass data using resolve and bindings to a component in views? I had success passing data to the controller, but it seems to not work with components. .config(function ($stateProvider) { $stateProvider .state(&apo ...

Steps for deactivating jQuery slider control until radio button is selected:

Looking to deactivate the operation of jQuery UI sliders until a radio button is selected. Despite my efforts, I have been unsuccessful in achieving this task and could use some guidance. For reference, here is a link to the code: http://jsfiddle.net/nlem3 ...

How to extract data from Firebase's snapshot.val() using React.js

I have a coding challenge where I need to retrieve the password from the userData object displayed in the console: -MeL7hm5pU3RGhvXnYlR: {name: "wed", password: "wed", userName: "wed"} Here is my code snippet: const Login = ...

Obtain data in JSON format through an xmlhttp request

I originally used jQuery for this task, but I now want to switch to regular JavaScript as I'll be incorporating it into phonegap. I aim to avoid relying on different JS frameworks every time I make a server request, which could potentially improve per ...

Distinguishing between Angular 4's componentInstance and debugElement.componentInstance

Recently, I was reading through the documentation on this site: https://angular.io/guide/testing component = fixture.debugElement.componentInstance component = fixture.componentInstance However, I am still unclear about the distinction between these two. ...

Passing parameters to Next.js pages

Here is my function: export async function getServerSideProps({ req }: any) { const user = ( await axios.get("http://localhost:4000/api/auth/status", { withCredentials: true, headers: { Cookie: `connect.sid=${req.cookies["c ...

Anomaly in the default checked state of checkboxes

I'm currently working on a project and encountering an issue with the code below. I need to incorporate a forEach() loop within getElements() instead of using map(). Additionally, I want the default state of a checkbox to remain checked even after nav ...