jeudi 13 avril 2017

Ember synchronous looping with service

How to achieve synchronous loop ? I am looping through an array having ids. With the id I am fetching records from an API and doing some computations.

What I want is to call a function or execute a piece of code only after one by one execution will get finish in the loop.

I have tried following code :

let cnt = 0;
let successFrwrd = 0;
let failReqFrwrd = 0;
let failRecapFrwrd = 0;
this.checkedItems.forEach((item) => {   
    self.get('store').query('instances', {
        filter : {
            id : item.get('id')
        }
    }).then(instances => {
        if (!instances.get('length')){
            throw new Error();
        }
        if (instances.get('status')===2){
            failReqFrwrd++;
            throw new Error();
        }
        if (instances.get('status')===4){
            failRecapFrwrd++;
            throw new Error();
        }
        return instances.save();
    }).then( () => {
        successFrwrd++;
    }).catch(() => {
        return null;
    });
    cnt++;
    if(cnt === this.checkedItems.length){
        if(successFrwrd > 0){
            console.log(successFrwrd+' Completed' );
        }
        if(failRecapFrwrd >0){
            console.log(failRecapFrwrd+' Recap Fails' );
        }
        if(failReqFrwrd>0){
            console.log(failReqFrwrd+' Request fails' );
        }
    }
});

But every time I am getting all counter value as ZERO. There might be more fail reasons i need to display.




Aucun commentaire:

Enregistrer un commentaire