JavaScript - untimely initiation of await functionality

I'm a beginner when it comes to using async and await, and I could really use some assistance.

In my code, there's a function called register which registers a user and sends their data to the server to create a "user profile". However, I'm running into an issue with another async function called login. This function redirects the user immediately after registration, so the "user profile" data is not being sent.

Take a look at my register function below:

async register(user: User) {
    try {
      const result = await this.afAuth.auth.createUserWithEmailAndPassword(user.email, user.password);
      await this.afAuth.auth.currentUser.updateProfile({
        displayName: user.displayName,
        photoURL: ""
      }).then(() => {
        let currentUser = result;
        let date = new Date().getTime();
        let userData = {
          email: currentUser.email,
          displayName: currentUser.displayName,
          uid: currentUser.uid,
          created: date,
        }
        this.database.list('users').set(userData.uid, userData).then(() => {
            return;
        }); //I want to continue after this line is called. 
    return; 
      }, function(error) {
        console.log(error)
      });
    } catch(e) {
      console.log(e);
    }
  }

It seems like my await might be in the wrong place. I need the login function to wait until the data is successfully .set...

If you have any insights on what I might be doing incorrectly, I would greatly appreciate your help. Thank you!

Answer №1

The benefit of utilizing async / await is that it eliminates the need to handle then() or catch().

async function signUp(user: User) {
  try {
    const result = await this.authService.auth.createUserWithEmailAndPassword(user.email, user.password);

    await this.authService.auth.currentUser.updateProfile({
      displayName: user.displayName,
      photoURL: ""
    });

    let currentUser = result;
    let date = new Date().getTime();
    let userData = {
      email: currentUser.email,
      displayName: currentUser.displayName,
      uid: currentUser.uid,
      created: date,
    };

    await this.database.list('users').set(userData.uid, userData)

    // Perform tasks after the above processes are completed

    return; 
  } catch(error) {
    console.log(error);
  }
};

Answer №2

With the use of await, you are able to pause execution for a promise to resolve. One major advantage of async-await is the elimination of then syntax and explicit promises. I am unsure why there is a combination of different styles being used in your code. It is quite straightforward to perform additional tasks after an await statement.

Below is some pseudocode. I have removed the try-catch block since your entire function already encapsulates it, rendering it somewhat redundant. If a promise is rejected, it will be transformed into an exception. In case an exception is encountered within a promise, it will result in a rejection which is then converted back into an exception. Exceptions occurring outside of promises remain as regular exceptions.

I saw that you posted TypeScript syntax, so I have added the TypeScript tag to your question. Keep in mind that TypeScript is distinct from Javascript.

async register(user: User) {
  const result = await createUser(...);
  await updateProfile(...);
  const userData = buildUserData(...);
  await setUserData(database, userData);
  console.log('more stuff after setUserData');
}

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

Encountered an error when attempting to use 'appendChild' on 'Node': the first parameter is not the correct type. It was able to work with some elements, but not with others

I'm currently working on a script that utilizes fetch to retrieve an external HTML file. The goal is to perform some operations to create two HTMLCollections and then iterate over them to display a div containing one element from each collection. Here ...

The act of transferring non-textual information into web-based applications

Is it possible for a user to copy and paste a selection of pixels from MSPaint into a browser-based app using JavaScript in current browsers? If not, will HTML5 make this possible in the future? Alternatively, could something like Flex or Silverlight be us ...

Can we improve the coding of this as it seems inefficient and uses up too much room?

Do you think there is a more efficient way to write this code? It seems quite impractical and takes up a lot of space. Essentially, it's about the random chance of obtaining a rarity, like acquiring an Uncommon sword. if (Math.random() * 100 < 100 ...

Creating a personalized aggregation function in a MySQL query

Presenting the data in tabular format: id | module_id | rating 1 | 421 | 3 2 | 421 | 5 3. | 5321 | 4 4 | 5321 | 5 5 | 5321 | 4 6 | 641 | 2 7 | ...

Making a RESTful API call using JavaScript

Can someone help me with making a call to a REST API using JavaScript, Ajax, or jQuery? curl -v -X PUT -H "Content-Type: application/json" -H "Accept: application/json" -X PUT --user user:password http://url -d "{\"name\": \"Marcus0.2\ ...

Is there a different option instead of relying on promises for asynchronous requests?

Let's consider a scenario where we have a basic front end application (perhaps using Angular) and a back end app. When the front end app performs a get request, in most cases, the Angular repository will initiate an $http.get request which will return ...

What is the method to determine if a date is larger or smaller than another using Javascript?

Using the inputText function retrieves the value entered in the textbox, while the hidden field value returns the current value. This is my current code snippet: if (inputText.value.length != 0) { if (inputText.value < document.getElementById(&apo ...

Do we need to utilize a server folder in Nuxt 3 if we have API endpoints?

In Nuxt 3, there is a dedicated server folder containing an api subfolder. Why should we utilize this when we already have API endpoints built with a server-side programming language like Laravel? Are they linked in any way? For instance, consider these ...

Encountering a problem while attempting to utilize node-postgres transactions - using a pooled client in conjunction with async/

I'm currently exploring the use of node-postgres transactions - found at this link Specifically, I am working on implementing a pooled client with async/await, but have encountered an error in doing so. The content of my db.js file, used below, is a ...

Grails array using jQuery autocomplete with findByAll() function

Hello everyone, I appreciate the assistance in advance! I am currently attempting to utilize Grails findByAll() in order to retrieve a list for use in the jQuery autocomplete feature found at this link: https://jqueryui.com/autocomplete/ I believe I am cl ...

What are the steps to incorporate metrics middleware for Socket IO notifications, specifically monitoring both emitted events and listener activity?

I am currently working on a project that involves tracking all socket.io notification transactions initiated by the server, resembling an API request/response counter to validate subscription validation. Our team is utilizing an express middleware to moni ...

Is there a way for me to retrieve the value nested within an object within another object from this Api response?

Hey there, I'm currently struggling to retrieve the value of faceit_elo from within the csgo object. I attempted using data.games.csgo.faceit_elo but unfortunately it didn't yield any results. Any suggestions on how to access this value would be ...

Tips for emphasizing a cube face when it is hovered over in THREE.js

I'm currently using a raycaster to determine the face of a cube and then apply color to it following this method: const colorAttribute = intersected.object.geometry.getAttribute('color'); colorAttribute.setXYZ(face.a, color.r, color.g, color ...

Guidelines for utilizing an image as a trigger for an if/else condition

I'm attempting to create a rock, paper, scissors-style game using jQuery. Here's how I envision it working: The player selects a picture by clicking on it, triggering the .click function. The computer then generates a random number between 1 an ...

Encountering an issue with connecting nodejs to mqlight

I have been working with nodejs and mqlight to test out some sample code provided on https://www.npmjs.com/package/mqlight. My current setup consists of nodejs 5.5.0 and npm version 3.3.12. To install mqlight, I used the command npm install mqlight. ...

What is the reason that self focus doesn't function in JavaScript?

Whenever an input element triggers a blur event, I want to focus on a specific element. The issue arises when I try to focus on the same element that caused the blur event. Why does this only work when the element I am focusing on is not the one triggeri ...

Determine whether the array of an object includes any elements from another array using Lodash

Each product in the array contains a unique structure that includes an ID, name, and materials list. The materials list consists of various materials with their own IDs and names. { id: 1, name: "product 1", materials: [ { id: 1, nam ...

Using React and TypeScript to Consume Context with Higher Order Components (HOC)

Trying to incorporate the example Consuming Context with a HOC from React's documentation (React 16.3) into TypeScript (2.8) has been quite challenging for me. Here is the snippet of code provided in the React manual: const ThemeContext = React.creat ...

What could be causing my Angular.js application to malfunction on IE7?

I have developed an Angular.js application that is working well on most browsers, but I am now facing compatibility issues with IE 7 and above. I have tried different approaches such as adding id="ng-app", using xmlns:ng, manually bootstrapping angular wi ...

What can you do to prevent a div from taking up the entire page if its height is not specified?

Currently, I am experiencing an issue with my layout. I have a hidden div with a fixed position that becomes visible when a button on the page is clicked. Inside this div, there is a table of buttons for the user to choose from. The problem arises when I ...