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

我知道这与返回诺言有关,并相信当我运行过滤器时,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;
};

最佳答案

为您的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

09-25 16:28