Employ an asynchronous immediately-invoked function expression within the callback

Can an asynchronous IIFE be used inside the callback function to avoid the error message "Promise returned in function argument where a void return was expected"? You can find an example here.

  signIn(email: string, password: string, course?: ICourse): Promise<void> {
    return new Promise<UserCredential>((resolve, reject) =>
      this.afAuth.signInWithEmailAndPassword(email, password).then(
        (res) => {
          resolve(res);
        },
        (error: { message: string }) => {
          reject(error);
          this.toastrService.warning('Something has gone wrong. Please try again.', 'Oops!');
          this.logger.debug('An error occurred during Email Sign In');
          this.logger.error(error.message);
        }
      )
    ).then(
      (result: UserCredential) => {
        if (course && result.user) {
          this.builderSignIn(course, result.user.uid);
        } else {
          if (result != null) {
            this.ngZone.run(() => {
              void this.router.navigate(['dashboard']);
            });
          }
        }
      },
      (error: { message: string }) => {
        this.toastrService.warning(error.message, 'Oops!');
      }
    );
  }

Answer №1

When using the new Promise executor callback, it is important to ensure that it returns void. Currently, an arrow function with a concise body is being passed which implicitly returns a value. To resolve this issue, you can simply modify the code as follows:

return new Promise((resolve, reject) => {
//                                      ^
   … /*
})
^ */

However, it is recommended not to use the Promise constructor at all. Instead, consider implementing the following approach:

signIn(email: string, password: string, course?: ICourse): Promise<void> {
  return this.afAuth.signInWithEmailAndPassword(email, password).then((result: UserCredential) => {
    if (course && result.user) {
      this.builderSignIn(course, result.user.uid);
    } else {
      if (result != null) {
        this.ngZone.run(() => {
          void this.router.navigate(['dashboard']);
        });
      }
    }
  }, (error: { message: string }) => {
    this.toastrService.warning('Something has gone wrong. Please try again.', 'Oops!');
    this.logger.debug('An error occurred during Email Sign In');
    this.logger.error(error.message);
    this.toastrService.warning(error.message, 'Oops!');
  });
}

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

Utilizing AngularJS to show content based on regular expressions using ng-show

With two images available, I need to display one image at a time based on an input regex pattern. Here is the code snippet: <input type="password" ng-model="password" placeholder="Enter Password"/> <img src="../close.png" ng-show="password != [ ...

Encountering a CSS syntax error within CodeSandbox when attempting to input code within brackets

Why is it that I don't see syntax errors in VSCode, but always encounter them in CodeSandbox? What could be causing this discrepancy and how can I resolve it? Any advice would be greatly appreciated. Thank you in advance. Here's an example of th ...

A step-by-step guide on how to implement a window scroll-controlled color transition

I've implemented jQuery code to change the opacity of my navbar's background as the user scrolls, transitioning from transparent to blue. Here's the snippet: $(window).scroll(function(){ var range = $(this).scrollTop(); var limit = 45 ...

Setting up Angular on Mac OS 10.13

I'm in the process of attempting to follow the quickstart guide for running Angular locally on MacOS 10.13.6. However, upon entering the initial command, I encountered a series of errors: npm install -g @angular/cli Here is the output: npm ERR! pat ...

"Step-by-step guide on populating a select box with data from the scope

Hey everyone, I'm new to using Angular and hoping for some help with a simple question. I've created a form (simplified version below) that I want users to see a live preview as they fill it out. Everything was going smoothly with regular field ...

Presenting a trio of distinct tables each accompanied by its own unique button option

I am attempting to create a functionality where there are 3 buttons and when a user clicks on one of them, it shows the corresponding table while hiding the other two. I have experimented with using getElementById to manipulate the display property of the ...

The Angular binding for loading does not correctly reflect changes in the HTML

Whenever a user clicks the save button, I want to display a loading indicator. The state changes correctly when the button is clicked, but for some reason, reverting back the value of the loading property on scope to false doesn't update the UI. Coul ...

The function webpack.validateSchema does not exist

Out of the blue, Webpack has thrown this error: Error: webpack.validateSchema is not defined Everything was running smoothly on Friday, but today it's not working. No new changes have been made to the master branch since Friday. Tried pruning NPM ...

Having trouble modifying a nested object array within a treeview component in Reactjs

Thanks for your help in advance! Question: I'm having trouble updating a nested object of an array in a treeview using Reactjs. Please refer to the code and sandbox link below: https://codesandbox.io/s/cocky-leakey-ptjt50?file=/src/Family.js Data O ...

How to Stop AJAX Requests Mid-Flight with JQuery's .ajax?

Similar Question: Stopping Ajax Requests in JavaScript with jQuery Below is the straightforward piece of code that I am currently using: $("#friend_search").keyup(function() { if($(this).val().length > 0) { obtainFriendlist($(this).va ...

Javascript onclick events failing to toggle video play/pause functionality

In my website, I have background music and a background video (webm format) embedded. I am facing an issue with making play/pause buttons in the form of png images work for both the video and the music. The background music is added using the embed tag wi ...

Monitoring inbound and outbound traffic in express middleware

I am in the process of incorporating a logger into my Express application. This logger needs to record both requests and responses (including status codes and body content) for each request made. My initial approach involves creating a middleware function ...

Implementing pagination in Firestore using React-Redux

I'm currently working on implementing pagination with Firebase and React Redux Toolkit. I've grasped the logic behind it, but I'm facing challenges when integrating it with Redux. Initially, my approach was to store the last document in the ...

"Troubleshooting the issue of Angular JS ng-click HTML being assigned via InnerHTML but not properly invoking

I am currently working on an AngularJS phonegap application. The HTML in this application consists of a blank table that is dynamically populated using JS Ajax. The Ajax request retrieves the necessary data and fills the table using innerHTML. Each button ...

Unable to fetch the value for the property 'toString' as it is undefined

custom-filter.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'customFilter' }) export class CustomFilterPipe implements PipeTransform { transform(items: any[], searchTerm: string): any { if (!sear ...

The use of $scope.$destroy may resolve memory leak issues, but it can also cause

In my TypeScript AngularJS application, I have a child directive that is dynamically generated. The template and controller are assigned at runtime based on the requirements of the situation, with multiple directives within the template. To display multipl ...

Advantages of using individual CSS files for components in React.js

As someone diving into the world of Web Development, I am currently honing my skills in React.js. I have grasped the concept of creating Components in React and applying styles to them. I'm curious, would separating CSS files for each React Component ...

Redux - The same reducers, containers, and components are yielding varying outcomes

update: Issue resolved by connecting a different variable to the mapStateToProps. I'm encountering some challenges with my react-redux application and I'm struggling to pinpoint the error in my setup. You can access the source code here. The f ...

Angular 10 and Typescript: Variables assigned within the change event become undefined

In my code, I initialize an Algolia input and set an onchange event to it. This initialization takes place in a service. algolia_data; random_var; this.http.post<any>('APIENDPOINT', formData).subscribe(data => { instance = places({ ...

How can I display a badge in my app when it is running using React Native?

For the past week, I've been dealing with an issue. My question is how can I display a new message badge without having to click on the message room when running my app. The badge should only show up after clicking on the message room. I see the badg ...