How to handle expired token in javascript?

We often have to work with so many different APIs in a project so what if we are currently calling all three APIs at once and the token expires?
Then all three API requests will call for a token refresh, but only one API will call the token refresh successfully and the other two APIs will fail because the token refresh mechanism will cancel the expiring token as soon as it is refreshed.

SOLVE
–request 1–> (token expired detection)
–request 2–> (later requests must wait for the token to return)
–request 3–> (no matter how many requests you have to wait)

The following code simulates the programming process when token expires

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const isTokenExpired = true
let token = 'Current token'

const refreshToken = (api_request_token) => {
console.log('Api request new token:', api_request_token)
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('\n')
resolve('This is new token')
}, 2000)
})
}

let refreshTokenRequest = null
const requestApi = async (url) => {
if (isTokenExpired) {
console.log('Request api with token expired:', url, token)
refreshTokenRequest = refreshTokenRequest ? refreshTokenRequest : refreshToken(url)
const newToken = await refreshTokenRequest
refreshTokenRequest = null
token = newToken
}

console.log('Request api:', url, token)
}

(main = () => {
requestApi('/me')
requestApi('/products')
requestApi('/posts')
})()

// Result
// Request api with token expired: /me Current token
// Api request new token: /me
// Request api with token expired: /products Current token
// Request api with token expired: /posts Current token


// Request api: /me This is new token
// Request api: /products This is new token
// Request api: /posts This is new token

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×