【问题标题】:Handle concurrency on token creation in nodejs在 nodejs 中处理令牌创建的并发性
【发布时间】:2021-10-19 08:04:50
【问题描述】:

我有一个端点用于创建一个新的访问令牌,以防前一个令牌过期。 流程如下:

  • 一个端点被调用
  • 返回的 statusCode 是 401,这意味着访问令牌不再有效
  • 我调用了提供新访问令牌的著名端点。

我的问题是:如果两个端点收到 401 作为 statusCode,我如何确保只调用一次访问令牌的创建?

【问题讨论】:

    标签: node.js concurrency axios es6-promise


    【解决方案1】:

    如果 axios 响应承诺在 4XX http 状态码上被拒绝,您可以使用 Promise.all。那么它可能是这样的。

    async function doRequests(token) {
        const firstReq = makeFirstReq(token)
        const secondReq = makeSecondReq(token)
        
        try {
            await Promise.all([firstReq, secondReq])
        } catch(error) {
            // You would have to wrap this in a try...catch too
            // also only do this if the status code is 4XX
            const newToken = await getFreshToken()
            await doRequests(newToken)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-30
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 2013-04-12
      • 2013-05-05
      • 1970-01-01
      相关资源
      最近更新 更多