繁体   English   中英

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

[英]Using asynchronous call when setting text D3

我有一些类似于以下代码:

 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。 即使您只是从异步修饰函数返回一个常量,您仍然会收到发送到d3 text()方法的promise。

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

幸运的是,当一个函数被传递时,它使用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