我有一个调用某些服务并返回响应的函数。如果响应为FALSE,则等待1秒再次询问服务(然后可能返回TRUE)。
如何调用我的函数" checkService()"曾经,并获得真正的价值? (第一次或第二次尝试,由函数决定)我在函数内部设置RET值,但函数总是返回第一个RET,因为setTimeout是异步的。
换句话说,我需要一些"睡眠"技巧或任何解决方案(也可能是jQuery)。
function checkService() {
//this may return TRUE or FALSE
var RET = someServiceResponse();
// here waits 1 second, then ask the service again
if( RET == true ) {
return true;
} else {
setTimeout(
function() {
//it must return the second response of the service
RET = someServiceResponse();
},
1000
);
// I want the checkService() return the response after de timeout
return RET;
}
}
function alertResponse() {
alert( checkService() );
}
答案 0 :(得分:2)
当您期望服务的结果时,您应该使用回调函数。
像这样:
function checkService(callback) {
//this may return TRUE or FALSE
var RET = someServiceResponse();
// here waits 1 second, then ask the service again
if( RET == true ) {
callback(RET);
} else {
setTimeout(
function() {
//it must return the second response of the service
RET = someServiceResponse();
callback(RET);
},
1000
);
// I want the checkService() return the response after de timeout
return RET;
}
}
因此,当您想要调用该服务时,您只需要执行以下操作:
checkService(function(status){
alert(status);
// Here some code after the webservice response
});
答案 1 :(得分:0)
谷歌搜索'javascript setTimeout回调'这里有一个方便的jsFiddle大约3个结果:
getData('http://fakedomain1234.com/userlist', writeData);
document.getElementById('output').innerHTML += "show this before data ...";
function getData(dataURI, callback) {
// Normally you would actually connect to a server here.
// We're just going to simulate a 3-second delay.
var timer = setTimeout(function () {
var dataArray = [123, 456, 789, 012, 345, 678];
callback(dataArray);
}, 3000);
}
function writeData(myData) {
console.log(myData);
}