客戶端須要不按期更新token,同時得保證在發送更新token同時其餘網絡請求掛起,不然會報token失效。待新token回來以後,從新發起掛起的請求。應服務端要求,更新token請求時,老token馬上失效數組
let token = 1 當前請求使用的token let refreshToken = false // 是否處於更新token中 let subscribers = []; // 掛起的請求數組 /** * 網絡請求入口 */ function callApi (data, time = 1000) { console.log('0000callApi=== type:' + data.type + ' token:' + token) if (refreshToken) { const retryOriginalRequest = new Promise((resolve) => { addSubscriber(()=> { resolve(request(time, data.type)) }) }); return retryOriginalRequest; } // 判斷是不是執行更新token if (data && (data.type == 'refreshToken')) { const newData = request(time, data.type) refreshToken = true return newData } return request(time, data.type) } /** * 執行網絡請求 */ function request(ms, type) { console.log('1111request=== type:' + type + ' token:' + token) return new Promise((resolve, reject) => { setTimeout(resolve, ms, type); }); } /** * token更新後,從新發起掛起的請求 */ function onAccessTokenFetched() { subscribers.forEach((callback)=>{ console.log('從新請求') callback(); }) refreshToken = false subscribers = []; } /** * push掛起的請求 * @param callback 掛起的請求 */ function addSubscriber(callback) { subscribers.push(callback) }
// before callApi({type: 'first', token}, 1000).then(consoleResponse) // Todo callApi({type: 'refreshToken', token}, 2000).then((v) => { token = 2 onAccessTokenFetched() consoleResponse(v) }) // doing callApi({type: 'second', token}, 2000).then(consoleResponse) callApi({type: 'third', token}, 2000).then(consoleResponse) callApi({type: 'four', token}, 2000).then(consoleResponse) callApi({type: 'five', token}, 2000).then(consoleResponse) // after setTimeout(() => callApi({type: 'six', token}, 2000).then(consoleResponse), 5000) function consoleResponse (v) { console.log('2222response===type:' + v + ' token:' + token) }
"0000callApi=== type:first token:1" "1111request=== type:first token:1" "0000callApi=== type:refreshToken token:1" "1111request=== type:refreshToken token:1" "0000callApi=== type:second token:1" "0000callApi=== type:third token:1" "0000callApi=== type:four token:1" "0000callApi=== type:five token:1" "2222response===type:first token:1" "從新請求" "1111request=== type:second token:2" "從新請求" "1111request=== type:third token:2" "從新請求" "1111request=== type:four token:2" "從新請求" "1111request=== type:five token:2" "2222response===type:refreshToken token:2" "2222response===type:second token:2" "2222response===type:third token:2" "2222response===type:four token:2" "2222response===type:five token:2" "0000callApi=== type:six token:2" "1111request=== type:six token:2" "2222response===type:six token:2"