Search code examples
javascriptasync-awaites6-promiseapollo

JS Promises: Relationship between .then syntax and async/await (Apollo client example)


Sorry for the bad question format, but I just don't know what's wrong here: I'm attaching a JWT token to an Apollo client (using apollo-boost), like this:

const client = new ApolloClient({
  uri: 'http://127.0.0.1:3000/graphql',
  // adding the auth header to all requests
  request: async operation => {
    try {
      const session = await Auth.currentSession()
      const token = session.accessToken.jwtToken
      operation.setContext({
        headers: {
          authorization: `Bearer ${token}`
        }
      })
    } catch(e) {
      return
    }
  }
})

This works. However, when I tried to convert this to .then syntax which I like better, it didn't work anymore. This is how I re-wrote it:

  request: operation => {
    Auth.currentSession().then(session => {
      const token = session.accessToken.jwtToken
      operation.setContext({
        headers: {
          authorization: `Bearer ${token}`
        }
      })
    }).catch(err => {
      return
    })
  }

What am I missing?


Solution

  • The async/await syntax is superior, try keep using that. If you have to target older browsers, I would suggest introducing a transpiler into your compilation pipeline instead of rewriting it to vanilla javascript by hand. If you are still interested in the "then" syntax, then here you are: the promise needs to be returned by the function.

    request: operation => {
        return Auth.currentSession().then(session => {
           ... 
        }).catch(err => {
          return
        })
    }