0

I am using AngularJS and Typescript. In my controller constructor, I make a call to a function that gets data and returns a promise. The promise is stored in the variable x.

x.then((data) => {
   //displays data
}, (err) => {
   //sends error message
});

Right now if the promise never resolves, it displays nothing. I want to use $timeout so that if the resolution of x takes too long it will display another message. I don't know how I can do it for promises. Calling this.$timeout(3000,true).then(() => {}); just delays the contents and I can delay a function. How can I abort if the promise doesn't resolve?

mysticalstick
  • 2,479
  • 5
  • 16
  • 21
  • Possible duplicate of [NodeJS Timeout a Promise if failed to complete in time](http://stackoverflow.com/questions/32461271/nodejs-timeout-a-promise-if-failed-to-complete-in-time) – Jared Smith Feb 21 '17 at 18:38
  • 1
    Possible duplicate of [Setting a timeout handler on a promise in angularjs](http://stackoverflow.com/questions/22994871/setting-a-timeout-handler-on-a-promise-in-angularjs) – Aurelio Feb 21 '17 at 18:47

1 Answers1

0

AngularJS v1.6 introduces the $q.race method which can be used to abort a promise:

var timeoutPromise = $timeout(null, delay).then(() => {throw "Timeout Abort" });

var timedPromise = $q.race(xPromise, timeoutPromise);

In this example, timedPromise will either resolve (fulfilled or rejected) with the results of xPromise or be rejected with the reason "Timeout Abort" whichever comes first.

georgeawg
  • 48,608
  • 13
  • 72
  • 95