gpt4 book ai didi

javascript - 如何在 D3 中使用资源对象(通过 Promise)?

转载 作者:行者123 更新时间:2023-12-03 09:30:14 24 4
gpt4 key购买 nike

更新:我意识到在游戏后期尝试执行数据库查找的形式很糟糕 - 我更新了代码,以便进入 D3 的原始数据已经包含我需要的信息创建我的图表,一切都按预期进行。

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

在下面的示例中,我尝试使用 FontAwesome 字形为我的节点创建“图标”。现在,在我的 getIcon() 函数中,如果并且仅当我立即返回 unicode 值时,我才能正确绘制节点图标/字形。一旦我做出 promise 并等待返回值,事情就会崩溃。在 Promise 有机会返回之前,D3 正在构建并渲染图。如何让 .text(getIcon) 等待将文本(字形图标)附加到节点,直到我们解决了我的 promise ?

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'; }
});
}

最佳答案

我不确定我是否理解您的 promise ,因为您没有使用 d 并且您还没有共享您的 promise 声明,但也许这就是您需要的结构类型...

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)
})
}

关于javascript - 如何在 D3 中使用资源对象(通过 Promise)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31534435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com