Axios请求拦截器等待ajax调用完成

Sis*_*sir 7 javascript ajax axios

我有一个用于axios调用的请求拦截器.它检查我的jwt令牌并在必要时调用刷新.

axios.interceptors.request.use((config) =>{

    const state = store.getState(); // get renewed state
    const time = Math.floor( new Date().getTime() / 1000 );

    if( 
        ! state.app.jwtRefreshOnRequest 
        && time >= state.jwt.expires - 120
        && state.jwt.refresh_before > time
    ){ // expiring in 2 min. refresh    

        //dispatch({type: 'JWT_REFRESH_REQUEST'});
        axios.get( API_BASE_URL + '/auth/refresh')
            .then(function(response){
                // dispatch({type: 'JWT_REFRESH_SUCCESS', payload: response.data});
                axios(config).then(resolve, reject);
            })
            .catch(function(err){               
                reject(err);
        });

    }       

    return config;
}); 
Run Code Online (Sandbox Code Playgroud)

此代码正确调用刷新并保存新令牌,但原始调用在拦截器请求完成之前不会成立,因此使用了过期令牌.

所以,我想我需要从拦截器进行同步调用.

Kei*_*ith 15

避免对HTTP请求进行同步调用,因为它们只会使您的应用程序挂起.

你需要做的是使调用代码异步 - 任何回调,承诺或异步相关的一般规则是,一旦你是异步,一切都需要是异步的.

在这里,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);
    })
}); 
Run Code Online (Sandbox Code Playgroud)

无论什么时候你看到then你正在处理Promise,一旦你是一切都需要返回一个Promise.

这是很多,如果你可以使用更方便async/ await-现代浏览器和transpilable支持新的关键字,如果你需要支持传统用户.有了这些,您可以将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;
}); 
Run Code Online (Sandbox Code Playgroud)