Devendra Verma Devendra Verma - 2 months ago 36
Node.js Question

Break from while which is inside forEach

Hello I have to break from the while loop. In that while loop I am calling an asynchronous function. I have to check if a certain field from the output of that async call is empty then I have to break from while else I will call again to that async function. I have tried this :

var options = {
headers : {
'Fk-Affiliate-Id':'xxxxxxx' ,
'Fk-Affiliate-Token' : 'xxxxxxxxxxxxxxxx'
}
};
var state = ['approved','tentative','cancelled','disapproved'];
state.forEach(element => {
options.url = 'https://affiliate-api.flipkart.net/affiliate/report/orders/detail/json?startDate='+startDate+'&endDate='+endDate+'&status='+element+'&offset=0';
loop : while(true){
// This is the async call
request.get(options, (err, res, body) => {
var data = JSON.parse(body);
console.log(data);
// I have to check whether next is empty or not ?
if(data.next === ''){
// I will perform some action on data here
break loop;
}
else{
// I will perform some action on data here
options.url = data.next;
}
});
}
});


But this showing error Unsyntactic break. How to break from while loop?

Answer

Seems like you don't need while loop there. You just want to stop when you reach desired result for one of the states. It means you need to wait until async call completes, and only after that proceed with another state. One of the solutions is to make calls synchronous (if possible). Another solution is to create separate function for each state processing, and call it from async call callback:

var state = ['approved','tentative','cancelled','disapproved'];
// starting with first state
processState(0);

function processState(stateIdx){
    if(stateIdx >= state.length){
        // we tried all states and no success.
        return;
    }
    // some code
    request.get(options, (err, res, body) => {
        // some code
        if(data.next !== ''){
            // we have more records for this state - call it one more time.   
            processState(stateIdx);
        } else {
            // done with this state, try next one.   
            processState(stateIdx + 1);
        }
    });
}