d3.js 工具提示显示“[object Promise]”而不是值

d3.js tooltip display "[object Promise]" instead of value

我尝试在工具提示中使用 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 和异步函数的初学者,你能帮帮我吗?

请看下面的link d3 documentation 按照这些例子,您在初始化时将工具提示内容放入变量中。

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

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