0

I have a React/ Flux app I am trying to return my "promiseSuccessData" but it has to be done outside of the ajax promise. Within the getChallengeData().

getChallengeData : function() {
    $.ajax({
        type: 'GET',
        url: baseUrl + '1.0/challenge/result/' + challengeId,
        crossDomain: true,
        xhrFields : {
            withCredentials : true
        },
    })
    .done(function(promiseSuccessData) {
        _challenges = promiseSuccessData;
    })
    .fail(function(jqXhr) {
        console.log(jqXhr)
        console.log('failed to register');
    });
    //This is where I want to "return _challenges" but _challenges isn't available here
},
pherris
  • 17,195
  • 8
  • 42
  • 58
elcapitan
  • 145
  • 1
  • 2
  • 13

2 Answers2

1

You should return the promise instead, and add the done handler outside where you need to use the value (I will assume that getChallengeData is a method of an object called myObj for the sake of the example):

getChallengeData : function() {
    return $.ajax({
        type: 'GET',
        url: baseUrl + '1.0/challenge/result/' + challengeId,
        crossDomain: true,
        xhrFields : {
            withCredentials : true
        },
    }).fail(function(jqXhr) {
        console.log(jqXhr)
        console.log('failed to register');
    });
},

And then, when you use it:

myObj.getChallengeData().done(function(promiseSuccessData) {
    _challenges = promiseSuccessData;
    //do something with challenges.
});
taxicala
  • 21,408
  • 7
  • 37
  • 66
0

Edit: Saw that the OP wanted to return the value of _challenges, not just work with it somehow.

You can't work with _challenges until the done function has run. When working with asynchronous Promises, you'll want to return the actual Promise (jQuery Deferred?) and have the caller attach his own handler.

function foo() {
    obj.getChallengeData()
        .done(function(challenges) {
            // Work with challenges here
        });
}

var obj = {
    getChallengeData : function() {
        return $.ajax({
            type: 'GET',
            url: baseUrl + '1.0/challenge/result/' + challengeId,
            crossDomain: true,
            xhrFields : {
                withCredentials : true
            },
        })
        .fail(function(jqXhr) {
            console.log(jqXhr)
            console.log('failed to register');
        });
    },
    // Other props
}
TbWill4321
  • 8,626
  • 3
  • 27
  • 25