gene b.
gene b.

Reputation: 11984

Can I return a Promise AND a custom return object from a function?

Maybe something is wrong with my design, but I have an Ajax function which

  1. Returns a Promise for downstream operations that depend on it
  2. But also has some business logic and needs to return a data object, which downstream operations also depend on

Example:

function insertEvent(newEventID, newEventStartTime, newEventEndTime) {

var promise = $.ajax({
    type : "post",
    dataType : "json",
    url : '/myapp/insertEvent',   
    data : JSON.stringify({'id' : newEventID,  'startTime':  newEventStartTime, 'endTime' : newEventEndTime 
                         })        
});

promise.then(function(data) {
    // some additional business logic...
    var resultObj = {'attr1' : attr1, 'attr2' : attr2};
});

return promise; // To outside dependendencies
                // But ALSO need to return resultObj to outside dependencies

}

Is this possible? The functions that call insertEvent need to

  1. get the result at the right time (only after Ajax completion)
  2. once there, they will look at resultObj from this function

    var resultObj = insertEvent(..);

In other words, I wish I could push a custom variable into the promise object, if it were possible.

Upvotes: 0

Views: 58

Answers (1)

jfriend00
jfriend00

Reputation: 707218

I don't follow exactly what you're trying to do, but here are a couple options if you really have multiple things to return:

  1. Return a promise from insertEvent() and make the resolved value of the returned promise be an object that has multiple properties/values in it. Then, when you do .then() on the promise, the resolved value will be an object with multiple properties.

  2. Return an object from insertEvent() where there are multiple properties in that object, one of which is the promise for the async part and other properties that represent things that are already known.

If you can't really do anything with the data until the promise is resolved, then #1 is probably a better way to go.

Here's an example of #1:

function insertEvent(newEventID, newEventStartTime, newEventEndTime) {

    return $.ajax({
        type : "post",
        dataType : "json",
        url : '/myapp/insertEvent',   
        data : JSON.stringify({'id' : newEventID,  'startTime':  newEventStartTime, 'endTime' : newEventEndTime 
                             })        
    }).then(function(data) {
        // some additional business logic...
        var resultObj = {'attr1' : attr1, 'attr2' : attr2};
        // return resultObj as the resolved value of the promise chain
        return resultObj;
    });
}

// usage
insertEvent(...).then(resultObj => {
    // use resultObj here
});

Upvotes: 2

Related Questions