Friday, May 17, 2024
91
rated 0 times [  97] [ 6]  / answers: 1 / hits: 20471  / 10 Years ago, mon, august 4, 2014, 12:00:00

I have a function that calls some service and returns the response. If the response is FALSE, it waits 1 second to ask the service again (which then probably returns TRUE).



How can I do to call my function checkService() once, and get the real value? (the first or second try, decided by the function) I set the RET value inside the function, but the functions always return the first RET, because the setTimeout is asynchronous.



In other words, I need some sleep trick, or any solution (may be jQuery too).



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

More From » asynchronous

 Answers
4

You should use a callback function when you expect a result from the service.



Like this :



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


So when you want to call the service, you just need to do :



checkService(function(status){
alert(status);

// Here some code after the webservice response
});

[#69914] Saturday, August 2, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devinjadong

Total Points: 711
Total Questions: 117
Total Answers: 100

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
devinjadong questions
Thu, Feb 17, 22, 00:00, 2 Years ago
Wed, Dec 8, 21, 00:00, 2 Years ago
Tue, Oct 27, 20, 00:00, 4 Years ago
Fri, Oct 18, 19, 00:00, 5 Years ago
;