Typescript - 在函数 return 块中使用 then 的值

Typescript - Using a value from then in function return block

我有这个功能:

function configureClient(): ApolloClient<ApolloCache<any>> {
    let myToken = getOktaToken().then(token => {
        return token
    });

    return new ApolloClient<InMemoryCache>({
        uri: "someUrl",
        cache: new InMemoryCache(),
        headers: {
            someAuth: myToken
        }
    });
}

我想在 return 块的 headers 中设置 someAuth: myToken 但是不确定如何使用这个 then 块。

另外补充:

一般来说,我会这样做,let myToken = await getOktaToken() - 但是我无法做到 async function configureClient(),因为 ApolloClient<ApolloCache<any>> 抱怨某些 ES3。我想这会奏效吗? Type 'typeof DefaultClient' in not a valid async function return type in ES5/ES3 because it does not refer to a Promise compatible constructor value

Promises 是异步的——您传递给 then 的回调在您的函数 return 之后被评估。您可以使整个 configureClient 函数 return 成为一个 Promise,但这意味着您将不得不更改您在应用程序其他地方使用它的方式(同样,因为在这一点上,整个客户端将异步初始化)。

function configureClient(): Promise<ApolloClient<ApolloCache<any>>> {
  return getOktaToken().then(token => {
    return new ApolloClient<InMemoryCache>({
      uri: "someUrl",
      cache: new InMemoryCache(),
      headers: {
        someAuth: token
      }
    });
  });
}

// or the equivalent using async/await syntax

async function configureClient(): Promise<ApolloClient<ApolloCache<any>>> {
  const token = await getOktaToken()
  return new ApolloClient<InMemoryCache>({
    uri: "someUrl",
    cache: new InMemoryCache(),
    headers: {
      someAuth: token
    }
  });
}

您可以延迟呈现您的应用程序,直到获取客户端。例如:



const App = () => {
  const [client, setClient] = useState(null)
  useEffect(() => {
    configureClient().then(setClient)
  }, [])

  if (!client) {
    return null
  }

  return (
    <ApolloProvider client={client}>
      ...
    </ApolloProvider>
  )
}

如果您有 headers 需要异步获取,但是,首选方法是使用 apollo-link-context。你应该 stop using Apollo Boost or better yet migrate to the latest Apollo Client. Then you can configure the links for your client instance and add a Context Link as shown here.