gpt4 book ai didi

javascript - 使用 jQuery 延迟或 promise 等待多个 $.post 调用完成

转载 作者:行者123 更新时间:2023-12-01 02:29:46 25 4
gpt4 key购买 nike

我正在尝试执行三个 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 和 Deferred,因为尽管这段代码通过嵌套回调很简单且易于理解,但我宁愿学习一个新工具并尽早进行切换。

最佳答案

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

关于javascript - 使用 jQuery 延迟或 promise 等待多个 $.post 调用完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22164037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com