问题
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