使用jQuery推迟或承诺等待多个$ .post调用完成 [英] using jQuery deferred or promise to wait for multiple $.post calls to finish

查看:116
本文介绍了使用jQuery推迟或承诺等待多个$ .post调用完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写三个jQuery帖子,将它们的结果设置为等于其范围之外的变量,然后在所有三个都返回之后(如果它们成功的话)执行另一个函数.现在,我正在嵌套嵌套的回调,如果可能的话,我想摆脱它.

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.

我查看了有关jQuery Promise和Deferreds的文档,但是还没有弄清楚如何将其与$ .post函数一起使用

I looked at the documentation for jQuery promise and deferreds, but haven't figured out how to use it with a $.post function

我当前的代码:

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

如果有一种更优雅的方法,我也很高兴也可以切换代码.我想开始使用Promise并且现在将其推迟,因为即使此代码简单易懂,而且嵌套的回调很容易理解,我还是希望学习一个新工具并尽快进行切换.

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.

推荐答案

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

这篇关于使用jQuery推迟或承诺等待多个$ .post调用完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆