[英]How to delay promise execute after defer is resolve
I used angular $q
to create a defer object like this: 我用angular $q
来创建一个像这样的延迟对象:
var defer = $q.defer();
var promise = defer.promise;
setTimeout(function(defer){
defer.resolve("nothing");
},2000,defer);
promise.then(function(){
//code here
});
So the code in promise will delay 2 seconds, but I want to know how to delay code execution after defer is resolved , so that I can delay code execution like this: 所以promise中的代码会延迟2秒,但是我想知道如何在延迟解决后延迟代码执行 ,这样我就可以像这样延迟代码执行:
promise.delay(1000);
when I get a promise from $http.post() 当我从$ http.post()得到承诺时
var promise = $http.post()...;
promise.then(function(){
// code
});
how to delay that code execute , since promise is resolved. 如何延迟代码执行,因为promise已经解决。
You should use $timeout
instead of setTimeout
, which also has the benefit of already returning a promise. 你应该使用$timeout
而不是setTimeout
,它还具有已经返回promise的好处。
To start the delay only after the initial promise is resolved, just put it inside a then
callback: 要仅在初始承诺解决后启动延迟,只需将其置于then
回调中:
promise.then(function(){
return $timeout(2000)
}).then(function(){
//code here
});
Just put this code in your revolved block. 只需将此代码放入旋转块即可。
setTimeout(() => {
//Code goes here.
},delayTime);
delayTime is the milliseconds of the delay. delayTime是延迟的毫秒数。
You need something like the following: 您需要以下内容:
var result = $q.defer();
$timeout(function() {
result.resolve('nothing');
}, 2000);
return result.promise;
and then later wherever you need it 然后在你需要它的地方
result.then(function(result) {
// if you need to delay the result handling then you need another $timeout call here like so:
$timeout(function() {
// do something with result
$scope.result = result;
}, 1000);
});
EDIT : Included another $timeout call in order to delay handling of resolved promise 编辑 :包括另一个$超时调用,以延迟处理已解决的承诺
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.