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

将ES2018 async/await函数转ES2015 Promise遇超时,求排查

问题分析与修复方案

你的ES2015版本代码有两个关键错误,这正是导致超时的核心原因:

1. 没有等待授权客户端初始化完成

google.auth.getClient()返回的是一个Promise,ES2018版本用await等待它解析出真正的授权客户端实例,但你的ES2015代码直接把这个Promise对象传给了google.drive()的auth参数——这完全无效,auth需要的是已完成授权的客户端实例,而不是一个未决的Promise,这会导致后续请求无法正确授权,一直卡在等待状态直到超时。

2. 错误使用了Drive客户端的API

google.drive({ version: 'v2', auth: ... })只是创建一个Drive客户端实例,它本身不是异步请求方法。你把创建客户端的逻辑和回调函数绑定在一起,完全跳过了实际发起文件列表请求的drive.files.list()方法,这意味着你的代码根本没有向Google API发送请求,自然不会有响应返回。


修复后的ES2015版本(Promise链风格,更贴合ES6习惯)

function connectGoogleAPI () {
  // 先获取授权客户端
  return google.auth.getClient({
    keyFile: path.join(__dirname, 'service-key.json'),
    scopes: 'https://www.googleapis.com/auth/drive.readonly'
  })
  .then(authClient => {
    // 创建Drive客户端实例
    const drive = google.drive({ version: 'v2', auth: authClient });
    // 发起文件列表请求(该方法返回Promise)
    return drive.files.list();
  })
  .then(response => {
    console.log(response.data);
    return response.data;
  })
  .catch(error => {
    console.error('请求出错:', error);
    throw error; // 抛出错误让调用方处理
  });
}

或者用Promise构造函数写法(适配回调偏好)

function connectGoogleAPI () {
  return new Promise((resolve, reject) => {
    // 第一步:获取授权客户端
    google.auth.getClient({
      keyFile: path.join(__dirname, 'service-key.json'),
      scopes: 'https://www.googleapis.com/auth/drive.readonly'
    })
    .then(authClient => {
      // 第二步:创建Drive客户端并发起请求
      const drive = google.drive({ version: 'v2', auth: authClient });
      drive.files.list((err, res) => {
        if (err) {
          reject(err);
          return;
        }
        console.log(res.data);
        resolve(res.data);
      });
    })
    .catch(err => {
      reject(err);
    });
  });
}

这两个修复版本都会:

  • 等待授权客户端初始化完成后再创建Drive客户端
  • 正确调用files.list()方法发起实际的API请求
  • 保持和ES2018版本一致的返回结果(res.data)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:28:06