0

I've read a plethora of questions here but still can't quite find the answer to this. That probably means I'm asking the wrong question but here goes anyway.

I'm trying to build my first app in a Vue.js using a REST api backend which will authenticate using JWT tokens.

I'm building layers that will at the bottom use axios to make the ajax request.

The layer above handles authentication, the JWT token, timeouts etc

then I'm into Vue with services, stores and components

So my question is how I build these layers such that at the authentication error i can intercept 401 returns that need a login refresh, passing the promise back up the chain.

I read here that I shouldn't create return new promise but should return the original promise.

What I'm seeing is that the return from getMails has undefined result.

So here's my code:

async function axios() { // emulate axios returning a promise
    return new Promise((resolve, reject) => {
      resolve('return from axios');
    })
}

// authentication layer. check for 401 and use Promise.reject
async function api() {
    await axios().then( 
      response => {
        // if ( response.status==401 )
        //     Promise.reject(response.status)
        console.log('api then: '+response)
        return Promise.resolve(response+'~return from api');    
      })
}

// services layer builds query params etc...
async function getMails() {
    return await api();
}

// vuex store to handle emails
// here just run js
getMails().then( function(response){
    console.log('back from getMails with:'+response);
    //let mails = response;
    //console.log('mails: '+mails);
})

see JSFiddle: https://jsfiddle.net/chrisby/y6eocrm0/

ChrisB
  • 611
  • 11
  • 24

1 Answers1

0

Thanks to Raja Jaganathan, I was missing a return on the await axios().then line, so the full working code is below. I've also updated the JSFiddle above.

async function axios() { // emulate axios returning a promise
    return new Promise((resolve, reject) => {
      resolve('return from axios');
    })
}

// authentication layer. check for 401 and use Promise.reject
async function api() {
  return axios().then( 
    response => {
      // if ( response.status==401 )
      //     Promise.reject(response.status)
      console.log('api then: '+response)
      return Promise.resolve(response+'~return from api');    
    })
}

// services layer builds query params etc...
async function getMails() {
  return api();
}

// vuex store to handle emails
// here just run js
getMails().then( function(response){
  console.log('back from getMails with:'+response);
  let mails = response;
  console.log('mails: '+mails);
})
ChrisB
  • 611
  • 11
  • 24