0

I presume this is a basic mistake, but as my searches made no effect, let's do it here anyway :)

I have a function returning a promise, but it runs so fast (because code is almost empty) that when .then() is called, it is too late and no event is called.

The reason why it happens is because that's a dummy code (for testing), so, the Promise concept is applied because of a situation where an actual async request is done.

So, is there a way to call the resolve/reject functions even after the function was processed? Or I would have to use lazy promises?

Update: I tried RSVP.defer() but didn't like its approach as it's not intuitive enough (requires some workaround to set .then() and .catch(), etc.

Marinho Brandão
  • 637
  • 1
  • 9
  • 30
  • 1
    Too late for what? No what kind of event is called? If you want to simulate some long-running asynchronous call, and latency is important, then try mocking it out with a routine which just waits for a few hundred milliseconds or whatever. If you could show a few code snippets, maybe people could be of more help. –  Sep 18 '15 at 07:43

1 Answers1

1

I have a function returning a promise, but it runs so fast (because code is almost empty) that when .then() is called, it is too late and no event is called.

That does not matter even one bit. Well behaved promises (like native promises, and virtually every library except old jQuery) are built with a guarantee that no matter when you attach the then handler - it will call the handler (and it will always do so asynchronously). A promise is just a value + time.

RSVP passes a suite of over 1000 tests to ensure this is always the case.

var p = Promise.resolve(); // create empty, already resolved promise

setTimeout(function(){ 
p.then(function(){
     // will always be called, eventually.
});
}, 1000000 + Math.random() * 10000000);
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504