D3 - 等待$ .ajax请求完成

时间:2016-11-19 19:00:41

标签: javascript d3.js

我正在研究一个d3项目,该项目使用d3.json()获取json文件,然后将响应传递给另一个名为update()的函数,该函数循环遍历数组并对每个项目运行ajax调用并返回结果。然后我尝试过滤掉所有为htrans属性定义的项目,这些项目在成功和失败的回调函数中都会添加。我遇到的问题是,当我执行过滤器时,worldMap变量似乎没有htrans属性,但是如果我在console.log中我可以看到它。我创建了CURRENT DATABASE LAYOUT来演示功能,并且还包含了以下代码。

我知道这与返回承诺有关,并且相信当我运行过滤器时,worldMap可能不完全完整。关于如何解决这个问题的任何想法?

var url = "https://gist.githubusercontent.com/jkeohan/d77d5ab47e018defe48d54f59acefb65/raw/ff61673eff2e7bf610c5a426c5bd9ca46da2a9da/worldmap_geojson.json";

d3.json(url,function(err, world)  {
  var worldMap = update(world);
  worldMap.features.filter(function(d){
   if (d) { console.log(d.htrans); return d }; // this doesn't have the   htrans property
  });
  console.log(worldMap); // this displays the the htrans property
});

function update(obj){
  obj.features.filter(function(d,i) {
   var code = d.properties.iso_a2.toLowerCase();
   var url = "https://www.googleapis.com/language/translate/v2?key=AIzaSyAADudga5Cdk2QlHDWF8UAHQEy-Z_ikHw8&target=" + code + "&q=Hello";  
   return $.when(ajaxCall(url)).then(doneCB, failCB);

   function doneCB(data){
    d.hello = data.data.translations[0].translatedText;
    d.htrans = true;
    //console.log(d)
    return d;
   }

   function failCB(data){
    d.hello = "";
    d.htrans = false;
    //console.log(d)
    return d;
  };

  function ajaxCall(url) {
   return $.ajax(url);
  };

 });//filter
 return obj;
};

1 个答案:

答案 0 :(得分:3)

为您的worldMap创建新承诺。

d3.json(url,function(err, world)  {
  var worldMap = new Promise( function(resolve, reject){
         update(world, resolve,reject);
  })

  worldMap.then(//do something if worldMap promise resolves something good
      function(val){          
        val.features.filter(function(d){
            if (d) { 
              console.log(d.htrans);
            };
        });
      }
  )
  .catch(// if error happened inside promise
    function(reason) {
        console.log('reason');
  });

});

并像这样解决这个承诺:

function update(obj, resolve, reject){
  obj.features.filter(function(d,i) {
   var code = d.properties.iso_a2.toLowerCase();
   var url = "https://www.googleapis.com/language/translate/v2?key=AIzaSyAADudga5Cdk2QlHDWF8UAHQEy-Z_ikHw8&target=" + code + "&q=Hello";  
   return $.when(ajaxCall(url)).then(doneCB, failCB);

   function doneCB(data){
    d.hello = data.data.translations[0].translatedText;
    d.htrans = true;
    //console.log(d)
    resolve(d); //resolve on success
   }

   function failCB(data){
    d.hello = "";
    d.htrans = false;
    //console.log(d)
    reject(d); //reject on error
  };

  function ajaxCall(url) {
   return $.ajax(url);
  };

 });//filter
 return obj;
};

看看:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise