避免对 HTTP 请求进行同步调用,因为它们只会使您的应用程序挂起。
这里您需要做的是使调用代码异步 - 与回调、promise 或异步相关的任何内容的一般规则是,一旦异步,所有内容都需要异步。
Here, axios.get
返回一个Promise
- 跟踪异步 HTTP 请求并在完成后解析的对象。你需要返回它,而不是config
.
我们通过返回一个新的来做到这一点Promise
- 如果需要新令牌的 HTTP 请求,它会等待,如果不需要,它可以resolve
立即地。
axios.interceptors.request.use(config =>
new Promise((resolve, reject) => {
// ... your code ...
axios.get( API_BASE_URL + '/auth/refresh')
.then(response => {
// Get your config from the response
const newConfig = getConfigFromResponse(response);
// Resolve the promise
resolve(newConfig);
}, reject);
// Or when you don't need an HTTP request just resolve
resolve(config);
})
});
每当你看到那个then
你正在处理Promise
,一旦你是一切需要返回一个Promise
.
This is much如果你可以使用的话会更容易async
/await
- 现代浏览器支持的新关键字,如果您需要支持旧用户,则可以转译。有了这些你就可以把Promise
内联调用await
关键词。
axios.interceptors.request.use(async config =>
// ... your code ...
if(/* We need to get the async token */) {
const response = await axios.get( API_BASE_URL + '/auth/refresh');
config = getConfigFromResponse(response);
}
return config;
});