【问题标题】:d3.js tooltip display "[object Promise]" instead of valued3.js 工具提示显示“[object Promise]”而不是值
【发布时间】:2019-01-23 17:12:40
【问题描述】:

我尝试使用 d3.js 在工具提示中显示异步函数返回的值。该函数很好地返回了该值,但是当我必须显示工具提示时,它包含 [object Promise] 而不是该值。

我使用 async/await 来处理这样的异步函数:

创建工具提示将包含的数据:

async function jsonMethodsArray(d) {
var arr = [];
// $.getJSON is asynchronous
// so wait until the end of its execution before proceeding to the other instructions
var json = await $.getJSON("method/data" + d.id + ".json", function(json) {
    for (var i = 0; i < json.nodes.length - 1; i++) {
        var node = json.nodes[i+1];
        arr.push(node.id);
    }
});
return arr;
}

创建并调用工具提示:

var tooltip = d3.tip()
.attr("class", "tooltip")
.offset([-8, 0])
.html(async function(d) {
    // jsonMethodsArray is asynchronous due to $.getJSON
    // so wait until the end of its execution before proceeding to the other instructions
    var methods = await jsonMethodsArray(d);
    console.log(methods);
    return methods.join("\n");
});
svg.call(tooltip);

显示或隐藏工具提示:

.on('mouseover', tooltip.show)
.on('mouseout', tooltip.hide)

显示工具提示中返回的数组的值,而不是显示 [object Promise]。

我是 Javascript、d3.js 和异步函数的初学者,你能帮帮我吗?

【问题讨论】:

  • 您能解释一下为什么在请求同步时使用异步调用吗?鼠标悬停操作?很可能在您执行时承诺尚未准备好tooltip.show
  • @Mulli 我使用异步调用,因为 $.getJSON 是异步的,因此要从 json 中获取数据,我必须使用异步并等待,否则我无法按时访问正确的值。在承诺的结果之后,我不知道如何使用 tooltip.show。
  • 我会尝试预加载工具提示以验证 toolip.show 是否正常。
  • 我该怎么做呢? @Mulli
  • 请查看以下链接d3-graph-gallery.com/graph/interactivity_tooltip.html 按照这些示例,您可以在初始化时将工具提示内容放入变量中。执行:var methods = await jsonMethodsArray(d); 开始/稍后将methods 附加到工具提示元素。

标签: javascript asynchronous d3.js promise tooltip


【解决方案1】:

请查看以下链接d3 documentation 按照这些示例,您可以在初始化时将工具提示内容放入变量中。

开始时执行:var methods = await jsonMethodsArray(d);

稍后将方法附加到工具提示元素

【讨论】:

    猜你喜欢
    • 2016-07-09
    • 2022-08-14
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多