js异步调用promise

这里已经使用了promise,为什么122行会先于117行调用?怎样确保在122行被调用前已经完成整个for循环?

img


另外,为了方便起见,之前在res.data使用的是纯数字作为字段名,但是发现在无法使用纯数字(或外加引号)作为字段名,也无法使用[[ ]]来用变量指代,有什么解决办法吗?

img

for (let i=parseInt(firstD);i<today+firstD;i++){
      zArr[i].cls='circle';
      date=`${y}${m}${d}`+'A';
      date2=`${y}${m}${d}`+'P';
      db.collection("checkin1").where({_id:18257509286}).get().then( res => {
        console.log(res.data[0]._20230418A);
        zArr[i].topColor=res.data[0]._20230418A;
        zArr[i].bottomColor=res.data[0].date2;
      })
    }
    console.log(zArr[18].topColor);

这是因为db.collection("checkin1").where({_id:18257509286}).get()是一个异步操作,它会返回一个Promise对象,而Promise对象是异步执行的。在for循环内部调用db.collection("checkin1").where({_id:18257509286}).get()时,它会返回一个Promise对象,然后立即执行下一次循环。
当所有循环结束后,Promise对象才会被解析并执行其回调函数,因此第二个console会比for循环内的console先执行。

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632