Dojo: async调用setTimeout + Deferred——>不工作

Dojo: async call with setTimeout + Deferred --> not working

本文关键字:工作 Deferred async 调用 setTimeout Dojo      更新时间:2023-09-26

想象页面上有一个Dashboard和一些Items。当页面加载时,我们希望这样处理它:

  1. 加载并渲染Dashboard
  2. 使用async call (dojo.Deferred + setTimeout)加载所有Items .
  3. Items添加到Dashboard

一旦Item被加载,我们将其添加到Dashboard中。在此异步加载期间,我们希望页面可用于交互(ui线程未冻结)。

代码应该看起来像这样:

var deferred = new Deffered();
setTimeout(function() {
  array.forEach(items, function(item, i) {
    loadItem();
    deferred.progress(i + ' - loaded');
  });
  deferred.resolve();
}, 0)
deferred.then(function() {
  addItemsToDashboard();  
}, function(err) {
}, function(progress) {
  console.debug('Update:', progress);
});

然而,这并没有像预期的那样工作。页面Items加载的整个过程中被冻结

有什么问题或如何处理的建议吗?

解决方案是使用setTimeout和递归函数,像这样:

var counter = 0;
recursiveFunc: function(element) {
  setTimeout(function() {
    // Do stuff for element[counter]
    if (++counter < numberOfElements) {
      recursiveFunc(element);
    }
  }, 0);
}
recursiveFunc(element[counter])
UI线程仍然会有bug,但至少它没有被冻结。这个解决方案被选为快速解决方案。长期以来,我们决定优化代码以摆脱同步XHR请求。