我有一些类似于以下内容的代码:
nodeEnter.append('text')
.text(async function(d) {
var count = await dispatch('GetCount', {
chosenNode: d
});
return count || 'N/A';
});
运行此程序时,显示的文本如下所示:
[object Promise]
该函数有效,但显然在 promise 返回任何内容之前返回。我将如何在类似于上述代码中等待操作?
我正在使用 Vuex 和 VueJs,这就是调度正在使用的内容。
d3.text()
方法不能很好地与 async/await 配合使用。
您看到的 promise 对象是因为async function()...
返回了一个 promise。即使你只是从异步修饰的函数返回一个常量,你仍然会收到一个发送到 d3text()
方法的承诺。
这是 d3text()
方法的来源
function textRemove() {
this.textContent = "";
}
function textConstant(value) {
return function() {
this.textContent = value;
};
}
function textFunction(value) {
return function() {
var v = value.apply(this, arguments);
this.textContent = v == null ? "" : v;
};
}
export default function(value) {
return arguments.length
? this.each(value == null
? textRemove : (typeof value === "function"
? textFunction
: textConstant)(value))
: this.node().textContent;
}
幸运的是,当一个函数被传递时,它是用绑定 d3 'this' 上下文的apply()
方法调用的,所以我们可以轻松地在 promise 的.then()
回调中执行textContent
赋值,就像这样
/*
Because the 'this' context changes below, need to grab 'dispatch' here
This is specific to Vuex implementation mentioned in the question
When using a different async function, just make sure it's within closure
*/
const dispatch = this.$store.dispatch
nodeEnter.append('text')
.text(function(d) {
dispatch('GetCount', {
chosenNode: d
}).then(val => {
this.textContent = val // This is normally done in d3's text() method
})
/*
Don't return anything.
d3's text() method will receive 'undefined'
and not update textContent
*/
// return count || 'N/A';
});