我有以下代码,如果 promise 在五秒后没有返回,则会显示一条消息:
$timeout(function () {
if (!$scope.promiseComplete && $scope.submitted) {
$scope.message = {
content: [{
title: '',
msg: 'Service down - created'
}],
type: 'error'
};
return;
}
}, 5000)
我的困境是我只想显示此消息本身两秒钟。我尝试了以下方法并且它有效,这是“嵌套”超时的反模式吗?
$timeout(function () {
if (!$scope.promiseComplete && $scope.submitted) {
$scope.message = {
content: [{
title: '',
msg: 'Service down - Railcar ASN created'
}],
type: 'error'
};
$timeout(function(){
$scope.message = null;
}, 2000)
return;
}
}, 5000)
更新:基于这里的答案是我所采用的:
$timeout(function () {
if (!$scope.promiseComplete && $scope.submitted) {
$scope.message = {
content: [{
title: '',
msg: 'Service down - created'
}],
type: 'error'
};
return $timeout(function(){
$scope.message = null;
}, 2000)
}
}, 5000)
最佳答案
$timeout
是基于 Promise 的,它返回一个可以链接的 Promise。是的,嵌套的 $timeout
或任何其他 promise may be an antipattern 。
这种 promise 链
$timeout(function () {
if (!$scope.promiseComplete && $scope.submitted) {
...
return $timeout(function(){
$scope.message = null;
}, 2000)
}
}, 5000)
保证嵌套不超过2层,并且可以利用top $timeout
返回的promise,整个promise链可以进行扩展或测试。
关于javascript - 超时时显示一条消息,仅两秒钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37423821/