从Promises异步更新DOM

async update DOM from Promises

本文关键字:DOM 更新 异步 Promises      更新时间:2023-09-26

我想通过我的承诺来更新DOM。我构建了一个承诺数组,并使用Promise.all:

运行它们。
function test(i){
  return Promise.resolve()
  .then(function() {
    // update the DOM
    document.getElementById('progress').innerHTML += i;
    return i;
  });
}
var loadSequence = [];
// loop through all the frames!
for (var i = 0; i < 9999; i++) {
  loadSequence.push(test(i));
}
Promise.all(loadSequence)
.then(function(){
  window.console.log('all set...');
});
http://codepen.io/nicolasrannou/pen/jbEVwr

我无法让DOM实时更新。只有当我所有的承诺都解决了,它才会更新DOM。

这是预期的行为吗?如果是这样,我该如何利用诺言。来实时更新我的DOM ?

我想使用承诺而不是"setTimeout(function, 1000)"hack,但我找不到好的方法来做到这一点。

在浏览器中,DOM队列发生变化,如果它们连续发生,而主事件队列没有一些"空闲标记",就像你的for循环一样,它们将在JS操作DOM完成时立即应用。参见:https://stackoverflow.com/a/31229816/1207049

为了在浏览器环境中克服这个问题,您可以使用setTimeout将代码执行块推送到不同的队列:

function test(i){
  return Promise.resolve()
  .then(function() {
    // update the DOM
    setTimeout(function() {
      document.getElementById('progress').innerHTML += i;
    }, 0);
    return i;
  });
}

如果没有setTimeout,每个更新元素innerHTML的指令都被推到同一个队列的末尾。使用setTimeout,它总是进入一个新的空队列,并且可以在主队列中的项目之前执行。