问题
I have following code , the problem is that obj is not inserted in the array arr.
let arr=[];
let frommilisec=1620000000;
let tomilisec=4680000000;
let slotmilisec=900000;
while(frommilisec<=tomilisec)
{
let timeslot_milisec=frommilisec+slotmilisec;
clinicslotsfunc(timeslot_milisec,maximumAppointment,clinicid,dated).then(results=>
{
let obj=results[0];
console.log(obj); // this displays { slot: '12:30:00', isbooked: 1 }
arr.push(obj);
});
console.log(arr) //this logs blank array
frommilisec=frommilisec+timeslot_milisec;
}
results[0] contains data { slot: '12:30:00', isbooked: 1 }
回答1:
Promise is an async operation, so you need to await a result of asynchronous operation:
async yourmethod()
{
let arr=[];
let frommilisec=1620000000;
let tomilisec=4680000000;
let slotmilisec=900000;
while(frommilisec<=tomilisec)
{
let timeslot_milisec=frommilisec+slotmilisec;
let result = await clinicslotsfunc(timeslot_milisec
, maximumAppointment, clinicid, dated);
arr.push(result);
});
console.log(arr);
frommilisec=frommilisec+timeslot_milisec;
return arr;
}
回答2:
Since clinicslotsfunc returns a promise (is asynchronously run), the '.then' part gets executed in the future at some time and therefore the obj is pushed to the array in future at some time provided the promise doesn't reject.
Now since you are doing console.log(arr); after this asynchronous task, it is empty because the clinicslotsfunc.then() would not have run immediately. So your array is always logged empty because the array will be filled in future.
来源:https://stackoverflow.com/questions/59476582/value-is-not-getting-inserted-in-the-array-array-returns-blank-values