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

批量向Google Cloud Storage上传对象仅成功400个,原因何在?

GCS批量写入仅生成部分文件的问题排查

1. 代码核心问题:回调与Promise混用导致未正确等待写入完成

你调用file.save()时传入了回调函数,这会让该方法不返回Promise,而是通过回调处理结果。此时promises.push()添加的其实是undefined,Promise.all(promises)根本不会等待真正的写入操作完成就继续下一批,导致大量写入请求被中断或未执行。

修复后的代码

const { Storage } = require("@google-cloud/storage");

const keyFilename = "path/to/service/account/file";
const projectId = "projectId";
const googleCloudConfig = { projectId, keyFilename };
const storage = new Storage(googleCloudConfig);
const bucket = storage.bucket("bucketName");

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const writeDocs = async () => {
  try {
    const arr = new Array(1000).fill({ test: "test"});
    const promises = [];
    for (let i=0; i < arr.length; i++) {
      const file = bucket.file(`test/${i}.json`);
      // 改用Promise风格调用,去掉回调
      const savePromise = file.save(JSON.stringify(arr[i]))
        .then(() => console.log(`saved JSON document ${i} to storage`));
      promises.push(savePromise);

      if (promises.length >= 50) {
        console.log("writing batch. total:", i+1)
        await Promise.all(promises);
        promises.length = 0;
        await sleep(1000);
      }
    }

    if (promises.length) {
      await Promise.all(promises);
    }
  } catch (error) {
    console.error(error);
  }
}

writeDocs();

2. 关于GCS速率限制

GCS公开的单桶写入速率上限是每秒1000次PUT/POST请求,你的写入频率是每1秒50次,远低于这个限制,不存在未公开的速率限制导致该问题。如果真遇到速率限制,GCS会返回明确的429 Too Many Requests错误,到时候可以加重试逻辑处理。

3. 额外排查方向

  • 检查未捕获的错误:原来的代码里回调中的错误不会被外层try/catch捕获,改用Promise后所有错误都会被捕获,方便排查问题。
  • 确认服务账号权限:确保服务账号有storage.objects.create权限,避免因权限不足导致写入失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 02:52:07