重复功能直到完成?
我有一个函数,我想按顺序重复运行,直到状态码检查正确。重复功能直到完成?
function check(id){
var status = 2;
var exit = 0;
// set status based on web request with ID param
switch(status){
// based on status code, output a message and set exit 0/1
}
/** Here I want the Function to repeat itself with a delay without skipping until exit is 1 **/
}
我试过使用async.whilst库,但我想不出如何保持ID参数和使用回调。
我也尝试了setTimeout方法,但它淹没了控制台并崩溃。
在此先感谢您提供的任何帮助。
编辑
下面是完整的代码,这是相当贫民窟,但我是新来的这个基于事件的东西
function checkStatusLoop(tradeID){ //checks if the trade is on-going or not (0 - done, 1 - ongoing)
var status = -1; // set default to active
var exit = 0;
manager.getOffer(tradeID, function(err, offer) {
if(err) throw err;
status = offer.state;
});
switch(status){
case 1:
console.log('Trade #' + tradeID + ' Invalid');
exit = 1;
break;
case 2:
console.log('Trade #' + tradeID + ' Active');
exit = 0;
break;
case 3:
console.log('Trade #' + tradeID + ' Accepted!');
exit = 1;
break;
case 4:
console.log('Trade #' + tradeID + ' Countered');
exit = 1;
break;
case 5:
console.log('Trade #' + tradeID + ' Expired');
exit = 1;
break;
case 6:
console.log('Trade #' + tradeID + ' Canceled');
exit = 1;
break;
case 7:
console.log('Trade #' + tradeID + ' Declined');
exit = 1;
break;
case 8:
console.log('Trade #' + tradeID + ' InvalidItems');
exit = 1;
break;
case 9:
console.log('Trade #' + tradeID + ' EmailPending');
exit = 0;
break;
case 10:
console.log('Trade #' + tradeID + ' EmailCanceled');
exit = 0;
break;
default:
console.log('Trade #' + tradeID + ' Bad State!');
exit = 1;
break;
}
if(exit == 0){
setTimeout(function(){
checkStatusLoop(tradeID);
}, 2000);
} else {
return (TradeOfferManager.getStateName(status));
}
}
这个库是从GitHub:https://github.com/DoctorMcKay/node-steam-tradeoffer-manager/wiki/TradeOfferManager#getofferid-callback
哎呦,显然有一个on('sentOfferChanged',很遗憾我花了很长时间在这
function check(id){
var status = 2; //default of 2
var exit = 0;
// set status based on web request with ID param
switch(status){
// based on status code, output a message and set exit 0/1
}
/** Here I want the Function to repeat itself with a delay without skipping until exit is 1 **/
//but I need the browser to update, so I cannot run check immedeately.
setTimeout(function() {
check(id);
}, 100)
}
?
哇,我不确定为什么它不能工作得更早,我没有在setTimeout函数中使用匿名函数,并且崩溃了,现在我觉得很愚蠢。 – user2837329
由于异步ajax请求仍然不会正常工作... – plalx
我试图做一些像while循环,直到变量设置从web请求,但它也是垃圾 – user2837329
不要忘记你的“web请求”可能是异步的,这意味着它不会返回一个值,控件将立即返回。因此,你的状态总是最终不确定。 – plalx
是的,我该怎么做?我刚刚也注意到了,第一次做node.js。虽然循环不起作用 – user2837329
这取决于您用来执行请求的API。它是一个基于承诺的API(返回一个承诺)?如果是这样的话,你可能想编写你的代码:function check(id){makeRequest(id).then(function(status){/ *其余的代码放在这里/ *}); }' – plalx