How to update DOM during a async call

心不动则不痛 提交于 2021-01-29 10:48:20

问题


If I have a async function as below

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

the second and third update don't happen until after the entire code block is completed. I saw online that it would be possible to fix this by wrapping the function in a setTimeout, however this doesn't work for me either:

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

Any idea how I can achieve this?


回答1:


The jquery dom manipulation shouldn't be stalled for function to get over. Here is a quick (and dirty) snippet which shows that:

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>


来源:https://stackoverflow.com/questions/50899469/how-to-update-dom-during-a-async-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!