0

I'm a beginner at Javascript, and I'm building an app to improve my skills. While making the login system for this app, I am having a problem with returning the data that I need from my 'main' parent function.

This is the main function with 2 'child' functions:

mock.onPost('/api/account/login').reply((config) => {

  // takes email and password from login form
  const { email, password } = JSON.parse(config.data);

  // create variables needed for user login
  let login_response = '';
  let memberId = '';
  let firstName = '';
  let lastName = '';

  function loginProcess(email, memberId, firstName, lastName, login_response) {

    if (login_response !== 'ok' ) {
      return [400, { message: 'Please check your email and password' }];
    }

    // let's save the information returned by the backend in the user object
    const db = {
      user: {
        id: memberId,
        email: email,
        firstName: firstName,
        lastName: lastName
      }
    };

    const { user } = db;

    // create the accessToken using the User ID returned by the backend
    const accessToken = jwt.sign(
      { id: user.id },
      JWT_SECRET,
      { expiresIn: JWT_EXPIRES_IN }
    );

    // if everything is ok with the login, we return the user object and an acccessToken
    return [200, { user, accessToken }];
  }

  // create the loginUser function that will make the request to the backend and database
  async function loginUser(email, password, memberId, login_response, firstName, lastName) {
    try {

      // request to flask endpoint to check if user exist and returns user information
      let loginResponse = await axios.get('http://localhost:5000/login/'+'?email='+email+'&password='+password)

      login_response = loginResponse.data.response;
      memberId = loginResponse.data.member_id;
      firstName = loginResponse.data.name.firstName;
      lastName = loginResponse.data.name.lastName;

      // returns user information and login response
      return loginProcess(email, memberId, firstName, lastName, login_response);

    } catch (err) {
      console.error(err);
    }
  }

  // lets run the loginUser function
  let res = loginUser(email, password, memberId, login_response, firstName, lastName);
});

Basically, the function loginProcess is function used inside the async function loginUser. Both are child functions from the main function mock.onPost('/api/account/login').reply((config).

I need that the main function mock.onPost('/api/account/login').reply((config) to also return the value returned by the child function loginProcess function, not sure how to do this.

I know that the child function is async, and from my understanding, the main function finishes 'running' and returns 'empty' values before the async finishes running. But I'm not able to figure out how to do this.

I would appreciate any help with this. If I'm not explaining myself correctly, please let me know.

Phil
  • 157,677
  • 23
  • 242
  • 245

0 Answers0