Reputation: 2210
I'm trying to do three jQuery posts, set their results equals to a variable outside their scope and then after all three have returned, if they are succcessful, execute another function. Right now I'm doing nested callbacks and would like to move away from that if possible.
I looked at the documentation for jQuery promise and deferreds, but haven't figured out how to use it with a $.post function
My current code:
var workout, diet, feedback
var postobj = { id: workoutId };
$.post("./RowingWorkouts/GetWorkoutUsingId", postobj, function(result) {
workout = result;
$.post("./Diet/GetDietUsingId", postobj, function(result) {
diet = result;
$.post("./RowingWorkouts/GetWorkoutFeedback", postobj, function(result) {
feedback = result;
renderCharts(workout, diet, feedback);
});
});
});
What I would like to do (pseudo code-ish):
var workout, diet, feedback
var postobj = { id: workoutId };
var getWorkout = $.post("./RowingWorkouts/GetWorkoutUsingId", postobj, function(result) {
workout = result;
});
var getDiet = $.post("./Diet/GetDietUsingId", postobj, function(result) {
diet = result;
});
var getFeedback = $.post("./RowingWorkouts/GetWorkoutFeedback", postobj, function(result) {
feedback = result;
});
// When all three are successful - I haven't gotten the when syntax to actually work yet
$.when(All3AreSuccessful).doThisOrSomething(renderCharts(workout, diet, feedback));
If there is a more elegant way to do it I'm happy to switch up my code too. I want to get into using promises and deferred now, because even though this code is simple and easy to understand with nested callbacks, I would rather learn a new tool and make the switch sooner rather than later.
Upvotes: 2
Views: 1628
Reputation: 388376
using $.when
var postobj = {
id: workoutId
};
var getWorkout = $.post("./RowingWorkouts/GetWorkoutUsingId", postobj);
var getDiet = $.post("./Diet/GetDietUsingId", postobj);
var getFeedback = $.post("./RowingWorkouts/GetWorkoutFeedback", postobj);
// When all three are successful - I haven't gotten the when syntax to actually work yet
$.when(getWorkout, getDiet, getFeedback).done(function (workout, diet, feedback) {
//each of the parameter is an array
renderCharts(workout[0], diet[0], feedback[0])
});
Upvotes: 5
Reputation: 707686
In your second example you can just pass multiple arguments to $.when()
like this and it will call the .done()
callback when all the arguments have resolved:
$.when(getWorkout, getDiet, getFeedback).done(function() {
renderCharts(workout, diet, feedback);
})
Examples shown here: https://api.jquery.com/jQuery.when/
Upvotes: 2