簡體   English   中英

如何在異步調用期間更新DOM

[英]How to update DOM during a async call

如果我有一個異步功能如下

async function predict_from_model() {
  $("#loading").html("first update")
  const model = await tf.loadModel('model.json');
  $("#loading").html("second update") //doesn't happen
  for (var i = 0; i < 100; i++) {
     const model = await tf.loadModel('model.json');
     $("#loading").html("more updates") //doesn't happen
  }
  ...
  <more code>
  ...
}

直到整個代碼塊完成后,第二和第三次更新才會發生。 我在線上看到可以通過將函數包裝在setTimeout來解決此問題,但這對我也不起作用:

async function predict_from_model() {
  $("#loading").html("first update")
  const model = await tf.loadModel('model.json');
  setTimeout(function() {
      $("#loading").html("loaded") //doesn't happen
  }, 0);
  for (var i = 0; i < 100; i++) {
     const model = await tf.loadModel('model.json');
     $("#loading").html("more updates") //doesn't happen
  }
  ...
  ...
  <more code>
  ...
}

知道我該如何實現嗎?

不應停止jQuery dom操作,以使功能無法克服。 這是一個快速(骯臟的)代碼段,它表明:

 var hardWork = function() { return new Promise((resolve, reject) => { setTimeout(_ => { console.log("hardwork over") resolve(); }, 2000) }) } async function dom() { $("#loading").html('Loading') $('#status').html('Loading at ' + new Date()) await hardWork(); $('#status').html('Loading at ' + new Date()) $("#loading").html('Loading 2') await hardWork(); $('#status').html('Loading again at ' + new Date()) $("#loading").html('Loading 3') } dom(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="status"> </p> <p id="loading"> </p> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM