使用jQuery延迟或承诺等待多个$ .post调用完成
我正在尝试做三个jQuerypost,将结果设置为等于其范围之外的变量,然后在所有三个返回后,如果它们成功,则执行另一个函数。 现在我正在进行嵌套回调,并希望尽可能远离它。
我查看了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并延迟使用,因为即使这个代码使用嵌套回调很简单易懂,我宁愿学习一个新工具并尽快进行切换。
使用$ .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]) });
在你的第二个例子中,你可以像这样将多个参数传递给$.when()
.done()
当所有参数都已解析时,它将调用.done()
回调:
$.when(getWorkout, getDiet, getFeedback).done(function() { renderCharts(workout, diet, feedback); })
此处显示的示例: https : //api.jquery.com/jQuery.when/