Angular2 - Utilizing Promises within a conditional block

I'm currently facing an issue where I need to await a response from my server in order to determine if an email is already taken or not. However, I am struggling to achieve this synchronously. TypeScript is indicating that the function isCorrectEmail() is of type void, which I can comprehend but cannot resolve. Any suggestions?

isEmailAvailable(){

    return new Promise( (resolve, reject) => {

        this.authService.checkemail(this.user.email).then(result => {

                let res = <any> result; 
                if (res.code == 0){
                    resolve(true);
                }
                else resolve(false); 

              }, (err) => {
               reject(false);
        });

    });

};


isCorrectEmail(){

    this.isEmailAvailable().then( (result) => { return result ; } );

};


 checkPersonalInfos() 
 {
   if ( this.isCorrectEmail() == true){...}
   ..
 }

Answer №1

Converting an asynchronous call into a synchronous one is not possible.

You have two choices: either enclose the code that requires the resulting value entirely within a then callback:

 validateUserInfo() 
 {
   this.checkAvailability().then(isAvailable => {
       if (isAvailable) { ... }
   }
 }

Alternatively, you can utilize the async/await syntax to mimic synchronous code appearance, but keep in mind it remains asynchronous, allowing other code to run during the await, and any returned result from the function will be encapsulated within a Promise():

 async validateUserInfo() 
 {
   if (await this.checkAvailability()) { ... }
   ...
 }

The presence of your verifyEmailAddress() function here serves no purpose towards the outcome. However, if its functionality becomes more intricate and essential, then it must return a Promise:

verifyEmailAddress(): Promise<boolean> {
    return this.checkAvailability().then(result => result);
};

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

Developing with Ionic 2 allows you to efficiently run a background service using Cordova

I am currently using Ionic 2 and I have a requirement for my app to perform certain tasks even when it is closed, similar to how Gmail continues to provide notifications all the time. After some research, I came across this documentation: https://ionicfr ...

What is the best way to initialize a value asynchronously for React context API in the latest version of NextJS, version

Currently, I'm working on implementing the React context API in my NextJS e-commerce application to manage a user's shopping cart. The challenge I'm facing is how to retrieve the cart contents from MongoDB to initiate the cart context. This ...

Is there a way to automatically populate the result input field with the dynamic calculation results from a dynamic calculator in Angular6?

My current challenge involves creating dynamic calculators with customizable fields. For example, I can generate a "Percentage Calculator" with specific input fields or a "Compound Interest" Calculator with different input requirements and formulas. Succes ...

Obtain both the key and value from an Object using Angular 2 or later

I have a unique Object structure that looks like this: myCustomComponent.ts this.customDetails = this.newParameter.details; //the custom object details are: //{0: "uniqueInfo", // 5: "differentInfo"} The information stored in my ...

A guide on incorporating multiple nested loops within a single table using Vue.js

Is it possible to loop through a multi-nested object collection while still displaying it in the same table? <table v-for="d in transaction.documents"> <tbody> <tr> <th>Document ID:</th> &l ...

Is it possible to detach keyboard events from mat-chip components?

Is there a way to allow editing of content within a mat-chip component? The process seems simple in HTML: <mat-chip contenteditable="true">Editable content</mat-chip> Check out the StackBlitz demo here While you can edit the content within ...

Managing empty functions as properties of an object in a React, Redux, and Typescript environment

I'm feeling a little uncertain about how to properly test my file when using an object with a function that returns void. Below are the details. type Pros={ studentid: StudentId pageId?: PageID closeForm: () => void } When it comes to creating ...

Using Javascript to perform redirects within a Rails application

Currently working on a Facebook application using Rails. There are certain pages that require users to be logged in, otherwise they will be directed to a "login" page. I am unable to use redirect_to for this purpose as the redirection must be done through ...

NodeJS Express throwing error as HTML on Angular frontend

I am currently facing an issue with my nodejs server that uses the next() function to catch errors. The problem is that the thrown error is being returned to the frontend in HTML format instead of JSON. I need help in changing it to JSON. Here is a snippe ...

FixPermissions not working properly | Discord.js EXPERT

I am currently in the process of updating my bot to be compatible with the latest version of discord.js. I have successfully made various changes, but I am facing an issue with the overwritePermissions section within my ticket command. For some reason, the ...

Dropped down list failing to display JSON data

I created a website where users can easily update their wifi passwords. The important information is stored in the file data/data.json, which includes details like room number, AP name, and password. [ {"Room": "room 1", "AP nam ...

Tips for making jQuery maphilight function properly?

Can someone assist me with Mapilight? I have been trying to get it to work but no success so far. Here are the script links in the head section of my HTML. <script type="text/javascript" src="/js/jquery.js"></script> <script type="text/ja ...

The "angular2-image-upload" npm package encountering a CORS issue

Using the angular2-image-upload library for uploading files has been a smooth process until recently. After upgrading from version 0.6.6 to 1.0.0-rc.1 to access new features in future, I encountered issues with image uploads. The errors I faced were: Tr ...

What is the best way to engage in conversations with several users using socket.io?

Currently, I am in the process of developing a chat application with authentication. The implementation involves socketio for real-time communication and jwt along with cookies for user authentication. The connection to the database has been successfully e ...

Sending a C# variable to an HTML file

I’m struggling to understand how I can use jQuery to access a variable from C# named sqlReq. My main objective is to be able to input my own SQL data into a PieChart. However, I’m unsure about how to call and define C# SQL requests in HTML or jQuery. ...

Issues with Bootstrap-slider.js functionality

I'm having trouble getting the bootstrap-slider.js library from to function correctly. All I see are textboxes instead of the slider components. You can view an example at I have verified that the CSS and JS files are pointing to the correct direc ...

Retrieve and access an array of objects from MongoDB

Assuming I have some data stored in MongoDB as follows - [ { _id: new ObjectId("63608e3c3b74ed27b5bdf6fa"), latitude: 24.3065, hotels: [ { name: "Saunders Oconnor", lat ...

How come the information I receive when I subscribe always seems to mysteriously disappear afterwards?

I've been working on a web project using Angular, and I've run into an issue with my code that's been causing problems for a while now. The problem lies in fetching data from a server that contains translations: getTranslations(): Observab ...

When using TypeScript, my sorting function returns a value of 0 for all time values

I have been trying to sort this JSON data by date using the provided code, but it does not seem to work as expected. Below is a snippet of my JSON: { "StatusCode":0, "StatusMessage":"OK", "StatusDescription":[ { "id":"1", ...

Displaying only the validation messages that are accurate according to the Vuetify rules

<v-text-field label='New Password' class="required" v-model='password' type='password' :rules="passwordRules" required> </v-text-field> passwordRules: [ value => !!value || 'Pl ...