您好我必须从while循环中断开。在while循环中,我调用异步函数。我必须检查该异步调用的输出中的某个字段是否为空,然后我必须中断,否则我将再次调用该异步函数。我试过这个:
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;
}
});
}
});
但是这显示错误Unsyntactic break。如何摆脱while循环?
答案 0 :(得分:1)
好像你在那里循环时不需要。您只想在其中一个州达到预期结果时停止。 这意味着您需要等到异步调用完成,然后才能继续执行另一个状态。其中一个解决方案是使呼叫同步(如果可能)。 另一个解决方案是为每个状态处理创建单独的函数,并从异步调用回调中调用它:
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);
}
});
}