【问题标题】:Pause outer function while nested function is still running在嵌套函数仍在运行时暂停外部函数
【发布时间】:2017-11-30 06:45:06
【问题描述】:

由于 Javascript 是单线程的,我真的不知道这会是什么问题,但它是这样的:我有一个被调用的函数,其中还有另一个函数。一旦 Javascript 开始执行内部函数,它就会与外部函数同时恢复,而我实际上希望它等到内部/嵌套函数完成然后继续。我希望这是可以理解的,但我将在 cmets 中进一步详细说明:

function foo() {
    "use strict";

    //get some json file
    $.getJSON("bar.json", function(data) {
        //calculate something with data
        //put the result in this div (innerHTML)
    });

    //display: block the div with results   
}

问题是即使计算尚未完成,它也会立即显示 div。然后它会在稍后抛出结果,这根本不是我想要的。我必须做出承诺或类似的事情吗?

提前感谢您的帮助。非常感谢。

【问题讨论】:

  • 因为$.getJSON 是异步的。请参阅this question 以了解如何使该调用成为同步调用。
  • 单线程但异步 -- 您需要利用callback 模式、使用基于promise 的方法或利用await。跨度>
  • @SpencerWieczorek 现在可以正常工作,但浏览器告诉我 “不推荐使用主线程上的同步 XMLHttpRequest [...]” - 使用 @987654328 是不好的做法@?

标签: javascript jquery json promise nested


【解决方案1】:

由于您的 $.getJSON() 是异步操作,因此您需要使用 Promise 来获得所需的结果。在then 块中,您要在其中使用结果显示块。或者,这一切都可以在您的 $.getJSON() 块中完成。如果你需要后者,你可以这样做:

function foo() {
    "use strict";

    //get some json file
    new Promise(function(resole, reject) {
      $.getJSON("bar.json", function(data) {
        //calculate something with data
        //put the result in this div (innerHTML)
        resolve(data)
      });
    }).then(function(data) {
       //display: block the div with results
    });
}

【讨论】:

    【解决方案2】:

    你不应该试图阻塞你的主线程。相反,将更改 divdisplay:block 的逻辑移动到在获取 JSON 后运行的回调中,如下所示:

    function foo() {
        "use strict";
    
        //get some json file
        $.getJSON("bar.json", function(data) {
    
            //calculate something with data
            //put the result in this div (innerHTML)
    
            //display: block the div with results   
        });
    
        // will continue executing 
    }
    

    【讨论】:

      【解决方案3】:

      Spencer Wieczorek 提供的非常有用的链接。我将代码更改为:

      function foo() {
         "use strict";
      
         //get some json file
         $.ajax({
           url: "bar.json",
           dataType: 'json',
           async: false,
           data: data,
           success: function(data) {
             //calculate something with data
             //put the result in this div (innerHTML)
           }
         });
         //display: block the div with results 
      }
      

      现在看来可以了。非常感谢您教我这种更好的获取 JSON 的方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-19
        • 2023-03-15
        相关资源
        最近更新 更多