如何从document.ready函数中的d3异步调用中获取存储的数据,以将其传递给函数

时间:2022-05-27 15:58:52

I was trying to store data from a async call to a variable/object/array outside the function. I have seen couple of solutions to make calls synchronous, using callbacks etc but none of them works for my scenario. This is what I am trying to do

我试图将数据从异步调用存储到函数外部的变量/对象/数组。我已经看到了几个使调用同步的解决方案,使用回调等,但它们都不适用于我的场景。这就是我想要做的

var x = [];
d3.json(url, response){
if(response{
   setInterval(funtion (){
   d3.json(url, response){
   x=response; 
   });
},5000);
}
}

$(document).ready(function(){
  console.log(x);
$.each(x, function(i,val){
  function(val);
});
});

1 个解决方案

#1


0  

You need to make deferred jquery function calls something like this:

您需要进行延迟的jquery函数调用,如下所示:

function test(){
          var defer = $.Deferred();
          setTimeout(function(){console.log("prints 1st");defer.resolve();},1000);
          return defer;
 }
function test2(){
       console.log("prints 2nd");
      return $.when();
 }
test().then(test2).then(function () {
           console.log("prints at the end.");    
 });

Here is a working example http://jsbin.com/payitucami/edit?html,console

这是一个工作示例http://jsbin.com/payitucami/edit?html,console

#1


0  

You need to make deferred jquery function calls something like this:

您需要进行延迟的jquery函数调用,如下所示:

function test(){
          var defer = $.Deferred();
          setTimeout(function(){console.log("prints 1st");defer.resolve();},1000);
          return defer;
 }
function test2(){
       console.log("prints 2nd");
      return $.when();
 }
test().then(test2).then(function () {
           console.log("prints at the end.");    
 });

Here is a working example http://jsbin.com/payitucami/edit?html,console

这是一个工作示例http://jsbin.com/payitucami/edit?html,console