You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将异步函数的返回结果传递给redirect重定向操作?

问题原因

oauthClient.createToken 是异步执行的Promise任务,JavaScript主线程不会等待它的回调执行完成,就会直接运行后续的res.redirect代码,导致拼接参数时accessToken还未被赋值。

解决方法

方法1:将重定向逻辑移入then回调

把重定向操作放到异步请求成功的回调里,确保拿到token后再执行重定向,同时补充错误场景的处理,避免请求无响应:

oauthClient.createToken(req.url)
  .then((authResponse) => {
    // 可省略多余的序列化+反序列化操作,直接用getJson返回的对象
    const newToken = authResponse.getJson()
    const accessToken = newToken.access_token
    // 拿到token后再执行重定向
    res.redirect(`http://localhost:3000/?token=${accessToken}`)
  })
  .catch((e) => {
    console.error(e)
    // 错误场景自定义处理逻辑,比如重定向到错误页
    res.redirect('http://localhost:3000/error')
  })
})

方法2:使用async/await语法简化异步逻辑

如果运行环境支持,用async/await写法可读性更高:

// 首先给外层路由处理函数加上async关键字,示例如下
app.get('/oauth/callback', async (req, res) => {
  try {
    const authResponse = await oauthClient.createToken(req.url)
    const accessToken = authResponse.getJson().access_token
    res.redirect(`http://localhost:3000/?token=${accessToken}`)
  } catch (e) {
    console.error(e)
    res.redirect('http://localhost:3000/error')
  }
})

内容的提问来源于stack exchange,提问作者Josh Simon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 07:57:01