JavaScript的同步选项 [英] JavaScript synchronization options

查看:134
本文介绍了JavaScript的同步选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在想,只要存在一个解决方案,在JavaScript code执行同步。例如,我有以下的情况:我试图从AJAX调用缓存一些响应值,问题是,它可能同时执行几个电话,因此它会导致竞争条件在code。所以,我很好奇,想找到该解决方案?任何一个有想法,怎么办?

I was wondering whenever exists a solution to perform synchronization in JavaScript code. For example I have the following case: I'm trying to cache some response values from AJAX call, the problem is, that it's possible to perform simultaneously several calls, therefore it leads to race condition in the code. So I'm very curious to find solution for that? Any one has idea that to do?

推荐答案

我已经找到了我的问题的解决方案。我不得不说这是不是完美的,因为我一直在寻找,但到目前为止,它的工作原理,我想更多的是暂时解决。

I have found solution for my problem. I have to say it's not that perfect as I was looking for, but so far it works and I think about that more as temporarily work around.

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

这篇关于JavaScript的同步选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆