gpt4 book ai didi

node.js - 从 forEach 内部的 while 中中断

转载 作者:太空宇宙 更新时间:2023-11-04 00:35:00 25 4
gpt4 key购买 nike

你好,我必须打破 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;
}
});
}
});

但这显示错误非语法中断。如何打破 while 循环?

最佳答案

似乎你不需要 while 循环。当您达到某一状态的所需结果时,您只想停止。这意味着您需要等到异步调用完成,然后才能继续另一个状态。解决方案之一是使调用同步(如果可能)。另一个解决方案是为每个状态处理创建单独的函数,并从异步调用回调中调用它:

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);
}
});
}

关于node.js - 从 forEach 内部的 while 中中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39462897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com