使用jQuery延迟或承诺等待多个$ .post调用完成

时间:2014-03-04 05:53:06

标签: javascript jquery ajax promise

我正在尝试做三个jQuery帖子,将结果设置为等于其范围之外的变量,然后在所有三个返回之后,如果它们成功,则执行另一个函数。现在我正在进行嵌套回调,并希望尽可能远离它。

我查看了jQuery promise和deferreds的文档,但还没弄明白如何将它与$ .post函数一起使用

我目前的代码:

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);
        });
    });
});

我想做什么(伪代码):

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));

如果有一种更优雅的方式,我也很乐意切换我的代码。我现在想要使用promises并推迟使用,因为即使这个代码使用嵌套回调很简单易懂,我宁愿学习一个新工具并尽快进行切换。

2 个答案:

答案 0 :(得分:5)

使用$.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])
});

答案 1 :(得分:2)

在你的第二个例子中,你可以像这样将$.when()多个参数传递给它,当所有参数都已解决时它会调用.done()回调:

$.when(getWorkout, getDiet, getFeedback).done(function() {
    renderCharts(workout, diet, feedback);
})

此处显示的示例:https://api.jquery.com/jQuery.when/