how to make Javascript setTimeout returns value in a function

后端 未结 2 1024
耶瑟儿~
耶瑟儿~ 2020-12-22 06:52

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).<

2条回答
  •  独厮守ぢ
    2020-12-22 07:22

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

提交回复
热议问题