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

使用Google Storage API时如何等待javascript回调执行完成再走后续逻辑

问题原因

file.save方法支持回调、Promise两种调用模式:当你传入回调参数时,方法不会返回Promise对象,此时await不会生效,代码会直接执行后续的console.log,因此会出现LastMessage比成功/错误日志先打印的问题。

解决方法

方案1:使用async/await + try/catch(推荐)

移除回调参数,直接等待file.save返回的Promise,用try/catch捕获异常:

try {
  await file.save(jsonData.trim(), { resumable: false })
  console.log('success')
} catch (error) {
  console.log('error')
}

console.log("LastMessage: Error or Success is received, only then log this message")

方案2:手动封装回调为Promise

如果需要保留回调逻辑,可手动将方法封装为Promise后再等待:

const saveResult = new Promise((resolve, reject) => {
  file.save(jsonData.trim(), { resumable: false }, function(error) {
    if (error) {
      console.log('error')
      reject(error)
    } else {
      console.log('success')
      resolve()
    }
  })
})
await saveResult

console.log("LastMessage: Error or Success is received, only then log this message")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:36:07