【问题标题】:Error parse multiples objects Property 'length' does not exist解析多个对象时出错 属性“长度”不存在
【发布时间】:2020-05-28 12:47:10
【问题描述】:

我对事件调用的函数有以下定义。

    forceUpdateLiveLocation: Returns Promise<false | true | LiveLocationChangedEvent[]>
     const forcedLiveLocation = await client.forceUpdateLiveLocation( message.from );
     console.log(forcedLiveLocation[0]);

有效,但这只返回第一个对象

[{
  lat: -2.510491,
  lng: -44.220796
}]

当我有几个事件时,他会构建这样的对象:

[ {
  lat: -2.510491,
  lng: -44.220796
},{
  lat: -2343434,
  lng: -443434343
}];

所以我尝试对对象执行for,但出现错误。

for(var i = 0; i < forcedLiveLocation.length; i++){
    console.log(forcedLiveLocation[i].lat.toString());   
}

错误:

“boolean |”类型不存在属性“length” LiveLocationChangedEvent[]'。 类型“false”上不存在属性“length”。

【问题讨论】:

  • 尝试打印console.log(forcedLiveLocation);

标签: javascript node.js typescript


【解决方案1】:

据我猜测是https://open-wa.github.io/wa-automate-nodejs/classes/client.html#forceupdatelivelocation 的文档:

聊天中显示实时位置的参与者列表。如果 聊天不存在,或聊天没有任何联系人 主动分享他们的生活位置,它会返回false。如果它是一个 与单个联系人聊天,如果数组中只有 1 个值 联系人的 livelocation 已开启。请注意。这应该只 每 30 秒左右调用一次。这迫使手机抓住 该号码的最新实时位置数据。这可以用于 与 onLiveLocation 结合使用(这将触发 onLiveLocation)。

因此,有时您会收到一系列事件,有时却没有。您需要根据不同的情况做出相应的回应。

if (Array.isArray(forcedLiveLocation)){ 
    for(var i = 0; i < forcedLiveLocation.length; i++){
        console.log(forcedLiveLocation[i].lat.toString());   
    }
} else {
    // do something else
}

【讨论】:

  • 完美它甚至解决了我在使用 setInterval 时遇到的问题,谢谢
【解决方案2】:

promise 应该返回boolLiveLocationChangedEvent[] 这些类型之一,因此您需要处理forceUpdateLiveLocation 函数的类型。

if(typeof forcedLiveLocation !== "boolean") // then do what ever you want

记录结果有效,因为console.log 与返回类型无关

【讨论】:

    猜你喜欢
    • 2022-07-01
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    相关资源
    最近更新 更多