javascript - 检查 promise 期间的进度

标签 javascript promise progress

我有一个关于 javascript 的 Promise api 的非常基本的问题。我有一个 promise 电话,可能需要一段时间才能完成。在处理过程中,我想通过一些加载百分比信息来报告 UI 中的进度。 then() 方法只是指向 Promise api 返回的时间。但是如何在处理时报告进度呢?

我尝试查看其他一些 stackoverflow 答案,但大多数都处理多个 Promise,并使用 setTimeOut() api。我只有一个 Promise api,并且不知道可能需要多少时间(取决于我调用时数据库中的数据)。由于我不知道可能需要的时间,因此我也不知道如何显示百分比信息。有什么建议么?

我正在使用基本的 JavaScript,并在代码中剔除可观察值,并且不能使用 React 或 Angular(无权访问它)。

最佳答案

I have a very basic question on promise api of javascript.

有一个非常基本的答案; Promise api 不支持“开箱即用”的进度。

don't know how much time it might take (depends on the data in the database at the time I make the call).

如果没有这些信息,就不可能提供任何有意义的进展。您需要做的第一件事是快速调用数据库以询问“需要如何加载 mch 数据”。然后,您应该以 block 的形式加载数据,并提供一种方法来在积累数据时将加载回 UI 的“ block X of Y”进行通信。简单来说,这是一种“流式传输”数据的基本手段。

这就是为什么,在您看到的地方,他们使用多个 promise 来完成此操作,其中每个“进度 promise ”在进度更新时都会解决,从而允许 UI 更新进度栏。

// fake promise to represent action which should take no more than 90s
var promise = new Promise((resolve) => {
    setTimeout(resolve,20000);
});

// reference to progressbar
var progressBar = document.querySelector('.progress');
var current = 0;

// repeating timer which updates every 5 secs
var updater = setInterval(() => {
   if(current >= 100)
       clearInterval(updater);
   // update by 5/90ths
   var updateAmount = (5/90) * 100;
   current += updateAmount;
   progressBar.style.width = current + "%";
},5000);

// when the long action resolves, set the progress bar to 100 and stop the repeating event
promise.then(() => {
   clearInterval(updater)
   progressBar.style.width = "100%";
   console.log("finished");
});
.progress-bar{
  width:100%;
  height:50px;
}

.progress{
   width:0%;
   height:100%;
   background-color:blue
}
<div class="progress-bar">
  <div class="progress"></div>
</div>

关于javascript - 检查 promise 期间的进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59318977/

相关文章:

javascript - arangodb难度教程: Node. js (io.js) 10分钟

javascript - 原生 JS Promise 重试包装器

html - 带有图像的进度条

inno-setup - 如何在 “PrepareToInstall”中显示进度?

javascript - Angular 嵌套 Controller 访问 ng-repeat 数据

javascript - U haz Backbone retroactive `on` 事件监听器?

javascript - 用于 Mapbox 服务的响应式 iframe

sql-server - nodejs mssql 和 promise 混淆

javascript - 使用 Jasmine 2 测试 Promise.then

html - 步进器 Angular 5|6 HTML CSS Onclick 事件