Reputation: 11984
Maybe something is wrong with my design, but I have an Ajax function which
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
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
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:
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.
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