JS Promises:.then 语法和 async/await 之间的关系(Apollo 客户端示例)

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

抱歉问题格式不好,但我只是不知道这里出了什么问题:我将 JWT 令牌附加到 Apollo 客户端(使用 apollo-boost),如下所示:

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
    }
  }
})

这行得通。但是,当我尝试将其转换为我更喜欢的 .then 语法时,它不再起作用了。这是我重写它的方式:

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

我错过了什么?

async/await 语法非常好,请继续使用它。如果您必须针对较旧的浏览器,我建议在您的编译管道中引入一个转译器,而不是手动将其重写为 vanilla javascript。如果您仍然对 "then" 语法感兴趣,那么您是:promise 需要由函数返回。

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