0
votes

I'm trying to figure out a way to resolve/reject a jquery promise in a function that is not directly accessible by the function that creates the promise/deferred.

The scenario is one where a request is sent to another machine and the response to this (which may or may not come) is handled by another function. As soon as I send the request I start a timer which rejects the promise on timeout. To resolve/reject the promise later based on the response from the remote machine, I make this promise accessible to both the send request and recv response (where it is resolved if the resp was a success) functions, however if the code that calls the function to send requests tries to send multiple requests this would not work.

Basically I would like to allow/process only one request at a time until that request is either resolved or rejected even if the calling code tries to send multiple requests. Any ideas on how to achieve this?

Sorry if I sound all over the place, am pretty new to this stuff.

1
Sounds like you've got things slightly wrong in your mind. In particular, if the request is made in the right way (with jQuery.ajax(...) or one of its shorthand methods), then all the resolving/rejecting will be managed for you by jQuery. All you need to do is to specify success/error handlers in one or more of a variety of ways and they will fire when the response arrives or the request times out. Post some code and I'm sure someone will be able to advise further. - Beetroot-Beetroot

1 Answers

0
votes

If I understand your question correctly, what you need to do is to configure the remote side to return a promise, and then invoke that routine and return its value from within a handler on the local side:

 Promise
    .when (ready_for_remote_call)
    .then (function () {return remote_action_returning_promise ();})
    .then (
        function () {console.log("remote succeeded");},
        function () {console.log("remote failed");}
    )
;

Note that this can be simplified as

    .then (remote_action_returning_promise)

which is completely different from

    .then (remote_action_returning_promise())

which would do nothing useful. Think about it.

This is an aspect of promises which is slightly hard to wrap your head around. Handlers may return promises, which then are "inserted", as it were, into the promise chain. The spec uses the expression that the promise "assumes the state" of the returned promise. In concrete terms, this means that if the returned promise is fulfilled, the invoking promise will be; if the returned promise is rejected, the invoking promise will be.

In other words, don't think of it as the remote side somehow rejecting a promise on the local side; think of it as returning a promise which if invoked as a handler the local side promise will assume the state of.