1

I need to have one function call a second function where the second function includes some setup code, an http callback to a REST server and then finely some cleanup code before returning to the first function. The idea is to have the first function then displays a result message after the second function is finished.

The following example returns from the second function before it finishes the callback so I don't get the results of the http success or error.

var saveData = function(_this){
        return new Promise(function(resolve,reject){
        resolve( _this.Save('SavExit') );
    });
};


saveData(this).then(function(httpResponse){
    // display response after http callback finishes
    console.log(httpResponse);
});


this.Save = function (lcAction) {
    // validate data

    $http.post('serverCallback.aspx',oSelectedVendor).
        success(function (data, status, headers, config) {

        // process data before returning;

        return true;
    }).
    error(function(data,status,headers,config){
        console.log(data);
        return false;
    });
};
Harvey Mushman
  • 615
  • 1
  • 11
  • 23
  • Drop that `saveData` function and just return the promise from the `Save` method. You even [don't need to use the `new Promise` constructor](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it), as `$http.post` already returns a promise. – Bergi Jan 22 '19 at 14:17
  • Don't use `.success` and `.error`, they're deprecated. Use `.then()` only. – Bergi Jan 22 '19 at 14:17

1 Answers1

1

You need to return Promise from the Save method:

this.Save = function (lcAction) {
    // validate data

    return $http.post('serverCallback.aspx',oSelectedVendor).
        success(function (data, status, headers, config) {

        // process data before returning;

        return true;
    }).
    error(function(data,status,headers,config){
        console.log(data);
        return false;
    });
};

Note return I added in front of $http.

In addition, since you return Promise from Save, you don't need another one in saveData:

var saveData = function(_this) {
    return _this.Save('SavExit')
};
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • Thank you very much, all the examples I found were very complicated and, I thought it was something silly but could not figure it out. You made my day! – Harvey Mushman Jan 22 '19 at 14:31