简体   繁体   中英

How to delay promise execute after defer is resolve

I used angular $q to create a defer object like this:

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.delay(1000);

when I get a promise from $http.post()

var promise = $http.post()...;
promise.then(function(){
     // code 
});

how to delay that code execute , since promise is resolved.

You should use $timeout instead of setTimeout , which also has the benefit of already returning a promise.

To start the delay only after the initial promise is resolved, just put it inside a then callback:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM