这里已经使用了promise,为什么122行会先于117行调用?怎样确保在122行被调用前已经完成整个for循环?
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先执行。
在promise产生之前,js 处理异步的方式是使用回调函数,一个回调函数执行完成,进行下一个回调函数。这样会导致层层嵌套,代码不清晰。容易进入回调地狱