如何在一个同步块中异步执行多个 ajax 调用 (jquery)
How to execute multiple ajax calls asynchronously in one synchronous block (jquery)
我知道如何使用 $.when 一次执行多个 ajax 调用。
例如:
$.when( d1, d2 ).done(function ( v1, v2 ) {
console.log( v1 ); // "Fish"
console.log( v2 ); // "Pizza"
})
但是,我想在一个方法中使用它,以便我可以多次使用它来 return 一个值(例如
function getDataFor(list) {
var data = [];
$.when(d1(list), d2(list)).done(function (v1, v2) {
console.log(v1);
console.log(v2);
data = [v1, v2];
});
return data;
}
正确的格式是什么?另外,在上面的例子中使用 .then over .done 基本上是没有用的,除非我计划在那个之后有另一个 promise 吗?
编辑:我不觉得这是一个重复的问题。虽然我明白为什么看起来像那样,但我真的只是想知道是否有一个开箱即用的或基于库的(例如,jquery/bluebird)包装器,如 .NET 的 WaitAll 方法,它需要一组异步调用并阻塞线程直到它们全部完成。我承认这是不可能的,但我不认为它是重复的。
不,一个函数不可能 return 多次,it's not possible to return any result variables before the ajax requests succeeded. You can however simply return a promise for the array of results - but for that you need to use then
instead of done
这样您就可以从回调中 return
。 (提示:从不使用done
或fail
)。
function getDataFor(list) {
return $.when(d1(list), d2(list)).then(function (v1, v2) {
// ^^^^^^ ^^^^
console.log(v1);
console.log(v2);
var data = [v1, v2];
return data;
// ^^^^^^
});
}
我知道如何使用 $.when 一次执行多个 ajax 调用。 例如:
$.when( d1, d2 ).done(function ( v1, v2 ) {
console.log( v1 ); // "Fish"
console.log( v2 ); // "Pizza"
})
但是,我想在一个方法中使用它,以便我可以多次使用它来 return 一个值(例如
function getDataFor(list) {
var data = [];
$.when(d1(list), d2(list)).done(function (v1, v2) {
console.log(v1);
console.log(v2);
data = [v1, v2];
});
return data;
}
正确的格式是什么?另外,在上面的例子中使用 .then over .done 基本上是没有用的,除非我计划在那个之后有另一个 promise 吗?
编辑:我不觉得这是一个重复的问题。虽然我明白为什么看起来像那样,但我真的只是想知道是否有一个开箱即用的或基于库的(例如,jquery/bluebird)包装器,如 .NET 的 WaitAll 方法,它需要一组异步调用并阻塞线程直到它们全部完成。我承认这是不可能的,但我不认为它是重复的。
不,一个函数不可能 return 多次,it's not possible to return any result variables before the ajax requests succeeded. You can however simply return a promise for the array of results - but for that you need to use then
instead of done
这样您就可以从回调中 return
。 (提示:从不使用done
或fail
)。
function getDataFor(list) {
return $.when(d1(list), d2(list)).then(function (v1, v2) {
// ^^^^^^ ^^^^
console.log(v1);
console.log(v2);
var data = [v1, v2];
return data;
// ^^^^^^
});
}