简体   繁体   English

设置文本D3时使用异步调用

[英]Using asynchronous call when setting text D3

I have some code similar to the following : 我有一些类似于以下代码:

 nodeEnter.append('text') .text(async function(d) { var count = await dispatch('GetCount', { chosenNode: d }); return count || 'N/A'; }); 

When running this, the text that shows looks like this : 运行此时,显示的文本如下所示:

[object Promise]

The function works but obviously returns before the promise returns anything. 该函数有效,但在promise返回任何内容之前显然会返回。 How would I go about awaiting an action in code similar to the above ? 我将如何在类似上述代码中等待操作?

I am using Vuex with VueJs, that's what the dispatch is working with. 我正在使用Vuex与VueJs,这就是调度正在使用的。

The d3 .text() method does not play well with async / await. d3 .text()方法与async / await不兼容。

The promise object you see is because async function()... is returning a promise. 你看到的promise对象是因为async function()...正在返回一个promise。 Even if you just return a constant from an async decorated function, you still get a promise sent to the d3 text() method. 即使您只是从异步修饰函数返回一个常量,您仍然会收到发送到d3 text()方法的promise。

Here is the source of d3's text() method 这是d3的text()方法的来源

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

Luckily, when a function is passed it is invoked with the apply() method which binds the d3 'this' context, so we can easily carry out the textContent assignment within the .then() callback of the promise, like so 幸运的是,当一个函数被传递时,它使用apply()方法调用d3'this'上下文,因此我们可以很容易地在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';
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM