Value is not getting inserted in the array,array returns blank values

吃可爱长大的小学妹 提交于 2020-01-05 07:12:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!