0

I am using jquery to send an ajax request to perform certain tasks and based on the result of that jquery GET response I am performing some action on Parse Js library.

e.g.

I have created a method like this to send the request.

sendRequest(URL, userId){
    return $.ajax({
        url: URL + userId,
        type: 'GET',
    }).fail((responseData) => {
        if (responseData.responseCode) {
            console.error(responseData.responseCode);
        }
    });
}

I am using it like this -

sendRequest(URL, userId)
.then(
       (data) => {
                   // Example
                   // Get some value from data and save it in Parse object
                    var GameScore = Parse.Object.extend("GameScore");
                    var gameScore = new GameScore();

                       gameScore.set("score", 1337);
                       gameScore.set("playerName", "Sean Plott");
                       gameScore.set("cheatMode", false);

                       return gameScore.save(); 
                 }
).then(
        (changedGameObj) => {
           console.log(changedGameObj);
           // At this point receiving a parse promise which is not resolved yet.
        },
        (error) => {
       }
);

I know that I am mixing jquery promise and Parse promise but don't know the solution of how to get resolved parse promises because jquery promises gets resolved earlier.

I am quite new to promise in js and please point me where I am wrong.

WitVault
  • 23,445
  • 19
  • 103
  • 133
  • You may also find that using the `function(data)` syntax works better than `(data) =>` for jQuery deferred. – Michael Cole Oct 21 '16 at 20:14
  • You ran into a [well-known problem](http://stackoverflow.com/q/32475978/1048572). Don't use jQuery promises :-) – Bergi Oct 24 '16 at 21:19

2 Answers2

0

From what I can see your promise chain is this (removing functions, etc):

$.ajax().fail().then().then(success(), error());

You can see the documentation for jQuery's deferred for more details.

There's two things to try:

1) Convert jQuery deferred to a real promise. I'd do this because I don't care to learn jQuery's deferred. You may need to dig in here so...

Suggested by Bergi: return Parse.Promise.resolve(jqueryPromise)

OR

2) Chain your Parse promises together in the same then():

sendRequest(URL, userId)       // This is jQuery deferred
.then( (data) => {
  // ...
  return gameScore.save()      // This is a promise
  .then( (changedGameObj) => { // success
    console.log(changedGameObj);
  }, (error) => {              // error
    console.warning(error);
  });                          // this whole promise is returned to the deferred.
})
.fail()                        // Back to jquery deferred.
.always()
.whatever()  
Community
  • 1
  • 1
Michael Cole
  • 15,473
  • 7
  • 79
  • 96
  • 1
    Yes had done exactly what you have written in answer part 2. Anyway thanks for help. – WitVault Oct 22 '16 at 16:27
  • Don't use #2. The error handler doesn't catch any errors from `sendRequest` like it did in the OP. – Bergi Oct 24 '16 at 21:14
  • @Bergi, people can do what they like. I added an example of how to do error handling. – Michael Cole Oct 27 '16 at 19:18
  • @MichaelCole Ah, sure they can, and often this pattern even is the correct one, I just meant that *the OP* probably shouldn't use it because it fails to meet the expectation that it does work the same as the error handling in his original code. – Bergi Oct 27 '16 at 19:41
0

Based on the Suggestion of Michael in first part I created a helper method to convert Jquery deferred to Parse promise. I feel that is much elegant way to do it.

convertJqueryToParsePromise(jqueryPromise) {
    let promise = new Parse.Promise();

    jqueryPromise
        .then(
            (results) => {
                promise.resolve(results);
            },
            (error) => {
                promise.reject(error);
            }
        );
    return promise;
}

Usage:

convertJqueryToParsePromise(sendRequest(URL, dataToSend))
.then(
       (success) => {
          // Do something here
       },
       (error) => {
       }
 );
WitVault
  • 23,445
  • 19
  • 103
  • 133
  • Much better: `return Parse.Promise.resolve(jqueryPromise)`. – Bergi Oct 24 '16 at 21:27
  • @Bergi can you please explain this terse syntax? It will help me to understand much better. May be you can post another answer. Thanks a lot. – WitVault Oct 25 '16 at 05:51
  • It's just the [`Promise.resolve`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve) function that is made for converting thenables to promises. It essentially does the same as your function, but it's proven correct and you don't have to write it yourself. – Bergi Oct 25 '16 at 10:47