开发者

Javascript Blocking Call

开发者 https://www.devze.com 2023-03-25 22:59 出处:网络
How do I do a blocking call in javasc开发者_如何学Cript? In the code below the alert at the last line of this code snippet hits before the code in if block completes which returns some value, by call

How do I do a blocking call in javasc开发者_如何学Cript?

In the code below the alert at the last line of this code snippet hits before the code in if block completes which returns some value, by calling chached.get method in different js file.

var getCachedData = function(_key){

    var retStr;
    if (_key != '' || _key != null) {
        cached.get(_key, function(data){
                   if(data){ 
                       alert('data = ' +data.value);
                       return data.value;
                   }
                   else{  
                        return undefine;              
                   }                    
                 });                  
    }
    alert('completed');
}


The cached.get method must be doing something asynchronously. The function you supply to that method as an argument appears to be a callback function that executes once the get method has returned successfully. If you need to run code that is dependant on the result of the call to cached.get, you will need to put it inside that callback.


It will depend on the library (i.e. whatever defines the behaviour of cached in your case) whether you can block or not. You'll have to provide more information about what cached is, or figure it out yourself.

However, generally speaking you want to avoid blocking in Javascript as much as possible, since Javascript runs in the UI thread for every major browser (as far as I know).

Instead of expecting to be able to block, rewrite your code so that you use data inside your callback function.

0

精彩评论

暂无评论...
验证码 换一张
取 消