【问题标题】:Argument type is not assignable to parameter of type参数类型不可分配给类型参数
【发布时间】:2019-06-24 02:05:56
【问题描述】:

我正在尝试通过执行以下操作来循环对象:

  const db = admin.firestore()
  const devicesRef = db.collection('devices')
  const devices = await devicesRef.get();
  devices.forEach(async (result, idx, array) => {

  });

但我得到一个错误:

'(result: any, idx: any, array: any) => Promise' 类型的参数不能分配给 '(result: QueryDocumentSnapshot) => void' 类型的参数。

我不太明白。如果我摆脱了idx, array,脚本可以完美运行,但我想知道最后一个循环何时执行,这就是为什么我添加idx, array...

任何想法错误消息可能意味着什么?

【问题讨论】:

  • 显然devices.forEach 不是标准Array.prototype.forEachdevicesRef.get 返回什么?
  • @jonrsharpe 它返回一个对象列表

标签: javascript typescript google-cloud-firestore


【解决方案1】:

假设devices 是一个对象数组,我认为您不能在那里分配您的函数,因为该函数只需要一个参数来获取单个设备。试试:

  const db = admin.firestore()
  const devicesRef = db.collection('devices')
  const result = await devicesRef.get();

  // adds all results to devices list
  List<any> devices = [];
  for (QueryDocumentSnapshot device : result.getResult()) {
    devices.add(device);
  }

  devices.forEach((device idx, array) => {
    if (idx === array.length -1) {
       // Do specific task
    }
    // some async function
    async (someOtherFunction) => {
       // do something with individual device
    }
});

【讨论】:

  • 感谢您的回答。在这个实现中,array 实际上会返回一个数组吗?因为我的目标是使用if (idx === array.length - 1) { 知道我何时处于循环的末尾
  • 如果您需要索引,您仍然可以按照自己的方式进行操作,但在 forEach 中删除 async 并稍后在函数中执行。我已经更新了答案。
  • 我仍然得到同样的错误:( Argument of type '(result: any, idx: any, array: any) =&gt; void' is not assignable to parameter of type '(result: QueryDocumentSnapshot) =&gt; void'.
  • 看起来,您得到的 QueryDocumentSnapshot 不是列表或数组。因此,您必须将其转换为列表。看到这个answer
  • 谢谢。我实际上意识到我可以做到devices.size 并在循环中保持一个计数器:)
猜你喜欢
  • 2021-06-14
  • 2018-08-10
  • 2021-10-17
  • 1970-01-01
  • 2021-02-03
  • 2020-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多