簡體   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