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

Flutter+Firebase应用Node.js清理脚本报错:await仅在async函数中有效

解决await is only valid in async function报错的问题

嗨,我看了你的代码,问题出在你在forEach的回调函数里使用了await,但这个回调本身不是async函数,JS引擎没法识别这个await,所以抛出了语法错误。另外还有几个小问题也得一起调整,才能让删除逻辑正常工作:

核心问题分析

  1. forEach的回调不是async函数,里面用await直接触发语法错误
  2. 你混用了.then()链式调用和async/await,容易导致流程失控,而且没有等待查询操作完成就结束了函数
  3. 时间计算有误:new Date()返回的是毫秒数,而Firebase Timestamp的_seconds是秒数,直接相减会导致时间判断逻辑错误

修正后的代码

async function mydelete() {
  try {
    // 用await替代.then(),让流程等待查询结果返回
    const snapshot = await cityRef.get();
    
    // 用for...of循环替代forEach,支持在循环内直接使用await
    for (const doc of snapshot.docs) {
      const docId = doc.id;
      if (docId.length === 4) {
        await db.collection('collection').doc(docId).delete();
      } else {
        // 把当前时间转成秒数,减去5小时对应的秒数(5*3600=18000)
        const fiveHoursAgoInSeconds = Math.floor(Date.now() / 1000) - 18000;
        if (doc.data().Timestamp._seconds < fiveHoursAgoInSeconds) {
          console.log(`Deleting old document: ${docId}`);
          await db.collection('collection').doc(docId).delete();
        } else {
          console.log(`Skipping document: ${docId} (not older than 5 hours)`);
        }
      }
    }
    console.log('Old document cleanup finished successfully');
  } catch (err) {
    console.error('Error during document cleanup:', err);
  }
}

关键修改点说明

  • 替换.then()为await:让异步流程更清晰,避免回调嵌套,同时确保函数等待查询完成后再执行后续逻辑
  • 用for...of替代forEach:forEach的回调函数无法直接兼容async/await,而for...of可以在async函数中正常使用await,确保每个删除操作完成后再进行下一个
  • 修正时间判断逻辑:把当前时间转换为秒数后再和Timestamp的_seconds比较,避免毫秒与秒的单位混乱
  • 为删除操作添加await:确保每个文档删除完成后再继续执行,不会因为异步操作未完成导致删除失效

这样调整后,你的脚本就能正确等待每个删除操作完成,也不会再出现await的语法错误啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 13:12:54