问题描述
我正在Angular(4)项目中使用Promises,但我对它们有一个疑问,我在文档中找不到对此的答复.
I'm using Promises in Angular (4) project and I have a question about them that I couldn't find a response to it in the docs.
当我创建一个Promise时,我基本上要等待服务/参与方的异步答复.但是我希望这个Promise保持多长时间处于待处理状态?有什么机制会在一段时间后终止它吗?这种等待/等待的概念有多可靠?
When I create a Promise, I basically wait for an async answer from a service/party. But how long should I expect this Promise to stay in pending state?Is there any mechanism that will terminate it after a while?How reliable is this concept of waiting/pending?
让我们假设我需要从繁忙的服务中获取一些数据,即使在等待几分钟后,它还是可以响应,无论响应的计算是一个资源密集型过程还是该服务与另一个服务相连反应非常缓慢.客户端上是否有任何东西会以某种方式终止我的承诺,并决定/强迫创建另一个人来再次询问我的数据?
Let's suppose that I need to get some data from a busy service that can answer even after few minutes of waiting, maybe more, no matter if the computing of the response is a resource intensive process or that service is linked with another one that is responding very slow.Is there anything on the client side that will somehow terminate my Promise and determine/force to create another one to ask again for my data?
有人建议升级到Observables,我会这样做,但是现在我想继续使用Promises,至少在代码的某些方面.
Someone suggested to upgrade to Observables, and I will do that, but for now I want to keep using Promises, at least for some areas of the code.
非常感谢
推荐答案
只要页面已加载,Promise
可以处于待处理状态.
A Promise
can be in pending state as long as the page is loaded.
您可以将呼叫包装在另一个Promise
中,在其中引入超时,如
You can wrap the call in another Promise
where you introduce a timeout like shown in
let wrappingPromise = new Promise((resolve, reject) => {
var error = false;
setTimeout(function(){
reject("some error");
}, 3000);
this.http.get(...).toPromise().then(res => {
if(!error) {
resolve(res.json);
}
});
});
达到超时时,这将导致错误.它将仍然等待接收完整的响应.一个Observable可能能够转发取消并关闭连接,以便在达到超时时甚至不再收到结果.这可能取决于具体的实现以及浏览器使用的浏览器API是否支持.
This will cause an error when the timeout is reached.It will still wait to receive the full response.An Observable might be able to forward a cancellation and close the connection, so that the result isn't even received anymore when the timeout is reached. This might depend on whether the concrete implementation and the browser used browser API supports that.
这篇关于Promise可以保持待定状态多长时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!