小编典典

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

ajax

我正在尝试做三个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));

如果有更优雅的方法,我也很乐意切换代码。我想开始使用Promise并立即进行延迟,因为即使此代码简单易懂,而且嵌套的回调很容易理解,我还是希望学习一个新工具并尽快进行切换。


阅读 435

收藏
2020-07-26

共1个答案

小编典典

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