我如何使用资源对象(通过承诺)与D3

How can I use resource objects (via promises) with D3?

本文关键字:承诺 D3 何使用 资源 对象      更新时间:2023-09-26

UPDATE:我意识到尝试在游戏后期执行数据库查找是一种糟糕的形式——我更新了我的代码,所以我进入D3的原始数据已经包含了我创建图表所需的信息,并且一切都像预期的那样工作。

我正在尝试构建一个力定向图,该图对节点元素执行数据库查找,以获取有关节点的附加信息,以便在图中进一步自定义。

在下面的例子中,我尝试使用FontAwesome字形来为我的节点创建"图标"。现在,在我的getIcon()函数中,如果且仅当我立即返回unicode值时,我才正确地绘制节点图标/字形。一旦我放入一个promise并等待返回值,事情就会中断。D3在promise有机会返回之前构建和渲染图形。我怎么能使.text(getIcon)等待追加文本(一个字形图标)到一个节点,直到我们解决了我的承诺?

node.append('text')
  .attr('text-anchor', 'middle')
  .attr('dominant-baseline', 'central')
  .style('font-family','FontAwesome')
  .style('font-size','24px')
  .text(getIcon)
  .style('fill', function (d) {
    return color(d.group);
  });

getIcon()定义如下:

function getIcon(d) {
  myPromise.then(function(data) {
    if(data.value) {
      return ''uf108';
    } else { return ''uf233'; }
  });
}

我不确定我理解你的承诺,因为你没有使用d,你没有分享你的承诺的声明,但也许这是你需要的结构类型…

node.append('text')
    .attr('text-anchor', 'middle')
    .attr('dominant-baseline', 'central')
    .style('font-family','FontAwesome')
    .style('font-size','24px')
    .each(getIcon)
    .style('fill', function (d) {
        return color(d.group);
    });
function getIcon(d) {
    var node = this;
    var myPromise = new Promise(function(resolve, reject){
        d3.json("data.json", function(error, glyphs){
            if(error || glyphs[d.char] === "undefined") reject(''uf233'); else resolve(glyphs[d.glyph]);
        })
    });
    myPromise.then(function(glyph) {
        d3.select(node).text(glyph)
    }).catch(function(defaultGlyph){
        d3.select(node).text(defaultGlyph)
    })
}

虽然我从未在D3上工作过,但我认为你需要先调用getIcon,然后再做节点。在promise回调中添加逻辑。就像

getIcon().then(function(data) {
   node.append('text')
  .attr('text-anchor', 'middle')
  .attr('dominant-baseline', 'central')
  .style('font-family','FontAwesome')
  .style('font-size','24px')
  .text(data)
  .style('fill', function (d) {
    return color(d.group);
  });
});

但是我意识到d参数将不可用。