Cross File Javascript Async Function

I am trying to have controller-view structure in my Vue project, and separate frontend display and frontend logic into two files. In the component, I would make a functional call to a controller method, and in the controller method, it will interact with backend API, but it seems like the async function is not working.

Here is the code in my Vue component:

import { authenticate } from '../controllers/userController'

function login() {
  if (email.value && password.value) {
    authenticate(email.value, password.value, remember.value).then((response) => {
      console.log(response)
    })
  } else {
    // Input Validation Failed
  }
}

And here is the implementation of the authenticate()

async function authenticate(email, password, remember) {
  axios.post(APIURL + '/v1/login', { email, password }, {
    headers: { 'X-Access-Key': APIAccessKey, 'X-Key-Secret': APIKeySecret }
  }).then((response) => {
    console.log(response)
    return {}
  }).catch((error) => {
    console.log(error)
    return {}
  })
}

export {
  authenticate
}

And this is what I see in the console:
enter image description here

As shown in the image, the response console log in the Vue Component returns undefined, and it is printed out before the response in the controller. It should have waited until the response is completed in the API call. So I am wondering what I did wrong, any help is appreciated.

Please ignore the 401 error, that error is intentionally introduced, the focus is that the console.log(response) should not be undefined, it should wait the response of the API call, and print out the API result

>Solution :

You need to return your promise from authenticate:

// No need to mark `async` since `await` isn't used
function authenticate(email, password, remember) {
  // add `return`
  return axios.post(APIURL + '/v1/login', { email, password }, {
    headers: { 'X-Access-Key': APIAccessKey, 'X-Key-Secret': APIKeySecret }
  }).then((response) => {
    console.log(response)
    return {}
  }).catch((error) => {
    console.log(error)
    return {}
  })
}

Otherwise, authenticate(...).then is the same as

authenticate();
Promise.resolve(undefined).then();

Leave a Reply