JavaScript同步选项

Art*_*ger 10 javascript ajax synchronization caching

我想知道什么时候存在一个在JavaScript代码中执行同步的解决方案.例如,我有以下情况:我正在尝试从AJAX调用缓存一些响应值,问题是,它可以同时执行多次调用,因此它会导致代码中的竞争条件.所以我很好奇为此寻找解决方案?谁有想法要做?

Cha*_*ant 8

我可以提供一个可能的解决方案,但没有看到代码...不完全确定你在做什么,但没有理由你不能这样做.

jQuery中的基本代码:(未经过测试和缩写......但我做过类似的事情)

var needAllThese = {};

$(function(){

      $.ajax("POST","/somepage.aspx",function(data) {
          needAllThese.A = "VALUE";
      });

      $.ajax("POST","/somepage2.aspx",function(data) {
          needAllThese.B = "VALUE";
      });

      $.ajax("POST","/somepage3.aspx",function(data) {
          needAllThese.C = "VALUE";
      });

      startWatching();
});

function startWatching() {
   if (!haveEverythingNeeded()) {
       setTimeout(startWatching,100);
       return;
   }
   everythingIsLoaded();
}

function haveEverythingNeeded() {
    return needAllThese.A && needAllThese.B && needAllThese.C;
}

function everythingIsLoaded() {
   alert("Everything is loaded!");
}
Run Code Online (Sandbox Code Playgroud)

编辑:(重新:你的评论)

你正在寻找回调,就像jQuery一样.

   var cache = {};

   function getSomeValue(key, callback) {
       if (cache[key]) callback( cache[key] );

       $.post( "url",  function(data) {
           setSomeValue(key,data);
           callback( cache[key] );
       }); 
   }

   function setSomeValue(key,val) {
        cache[key] = val;
   }

   $(function(){       
        // not sure you would need this, given the code above
        for ( var i = 0; i < some_length; ++i)  {
            $.post( "url", function(data){ 
                setSomeValue("somekey",data); 
            });
        }

        getSomeValue("somekey",function(val){            
             $("#element").txt( val );              
        };            
    });
Run Code Online (Sandbox Code Playgroud)


ffo*_*orw 6

Javascript本质上是单线程的,至少对于普通的浏览器环境而言.永远不会有两个同时执行访问同一文档的脚本.(新的Javascript工作线程在这里可能是一个例外,但它们根本不是为了访问文档,只是为了通过消息传递进行通信).

  • Javascript 可能是单线程的,但您可能会遇到竞争条件,无法保证发出异步请求的顺序、何时完成等。对于 Firefox 插件和多个窗口尤其如此。 (2认同)

Art*_*ger 4

我已经找到了解决我的问题的方法。我不得不说它并不像我想要的那么完美,但到目前为止它是有效的,我认为这更多是暂时的解决办法。

$.post( "url1", function( data)
{
     // do some computation on data and then
     setSomeValue( data);
});

var setSomeValue = ( function()
{
    var cache = {};
    return function( data)
    {
        if ( cache[data] == "updating")
        {
             setTimeout( function(){ setSomeValue( data);}, 100);
             return;
        }
        if ( !cache[date])
        {
             cache[date] = updating;
             $.post( "url2", function( another_data)
             {
                  //make heavy computation on another_data
                  cache[data] = value;
                  // update the UI with value
             });
        }
        else
        {
             //update the UI using cached value
        }
    }
})();
Run Code Online (Sandbox Code Playgroud)