可能重复:
将Deferred数组传递给$ .when()
无论如何传递jquery延迟$ .when ajax函数数组?例:
var arr = [
$.getJSON(window.location, function() { alert('yes') }),
$.getJSON(window.location, function() { alert('yes') })
]
$.when(arr).then(function(a, b) {
});
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
关于如何使用Jquery.deferred来生成慢同步函数的快速问题会返回一个promise.到目前为止我所做的是:
function sayIt(ms) {
setTimeout( function() { console.log('what I say'); }, ms);
}
function doIt() {
return $.Deferred( function() { sayIt(2000); }).promise();
}
doIt().then( function() { console.log('ah'); });
Run Code Online (Sandbox Code Playgroud)
sayIt(2000)总是通过,但'then'之后的链式函数永远不会触发.
如果我这样做:
doIt().then( console.log('ah'));
Run Code Online (Sandbox Code Playgroud)
'啊'马上出现,然后我说'我说'2000ms之后 - 我想要的当然是相反的 - 两秒后我得到'我说的',然后'啊'.
任何建议赞赏!
我试图找出jQuery的延迟api使用文档和其他人写的代码,但发现它非常令人困惑.我想知道如果看下面的功能,你可以解释一下
dfd.resolve的意义是什么?这是否意味着fadeOut是完整的,即它只在fadeOut完成后执行?这是否将延迟对象传递给jQuery fadeOut函数?
promise.promise(); 退回?为什么要调用promise(); 在承诺财产?
你能解释一下这段代码吗?
hide: function() {
if (this.el.is(":visible") === false) {
return null;
}
promise = $.Deferred(_.bind(function(dfd) {
this.el.fadeOut('fast', dfd.resolve)}, this));
return promise.promise();
},
Run Code Online (Sandbox Code Playgroud)我试图通过jQuery迁移到使用promises.在我的原始代码中,我有一个回调参数,它接受修改后的数据:
var getRss = function (url, fnLoad) {
$.get(url, function (data) {
var items = [];
$(data).find('item').each(function (index) {
items.push({
title: $(this).find('title').text(),
pubDate: $(this).find('pubDate').text()
});
});
fnLoad(items);
});
}
Run Code Online (Sandbox Code Playgroud)
我尝试更改为promise,但"done"返回未修改的数据而不是解析的数据:
var getRss = function (url) {
return $.get(url).done(function (data) {
var items = [];
$(data).find('item').each(function (index) {
items.push({
title: $(this).find('title').text(),
pubDate: $(this).find('pubDate').text()
});
});
});
}
Run Code Online (Sandbox Code Playgroud)
然后像下面一样使用它,但我得到原始的XML版本,而不是转换为对象的修改版本:
getRss('/myurl').done(function (data) {
$('body').append(template('#template', data));
});
Run Code Online (Sandbox Code Playgroud) 我试图抓住jquery中的延迟对象,但仍然遇到麻烦.基本上我有一系列我想要运行的函数,其中函数1的结果决定了第二个函数中的逻辑.
我不确定我是否必须在某处调用管道方法或者只是使用then(),但无论如何我都会失败.如果你看第一个函数,有一个名为data的对象,我想传递给第二个.
function run() {
var data1 = {};
var data2 = {};
var body = $('body');
$.when(first()).then(second()).done(constructData);
function first() {
var d = new $.Deferred();
var data = {} //arbitrary data set that i want to send to second
data.message = 'first message';
data.id = 1234;
body.append('First done');
//return data object? add it to the resolve method?
d.resolve();
}
function second(data) { //how do I get this data object?
var d = new $.Deferred();
body.append('Data from first:');
body.append('Second done'); …Run Code Online (Sandbox Code Playgroud) 好的,我知道这个话题已经多次讨论过,但我找不到解决问题的答案.
所以我试着做一个简单的想法:我正在创建一个字符串,如:distance is : " + CalculateDistance(position);
想要的结果是这样的distance is 5kms (8min).
CalculateDistance(position)是一个调用名为DistanceMatrix的Google地图API的函数来计算两点之间的距离.此处记录了 API ,并且给定的示例完美无缺.我这样改编:
function CalculateDistance(position)
{
var service = new google.maps.DistanceMatrixService();
var destination = new google.maps.LatLng(/* some lat/lng */);
service.getDistanceMatrix(
{
origins: [position],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK)
{
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var results = response.rows[0].elements;
distanceMatrixResult = results[0].distance.text + " …Run Code Online (Sandbox Code Playgroud) 我正在使用JQuery v2.0.0
我正在尝试理解延迟对象,我得到了意想不到的结果.即使此处没有可见或已知错误,也会触发fail().
function foo1() { alert('testing'); }
$.when(foo1())
.done(alert('success'))
.fail(alert('fail'))
Run Code Online (Sandbox Code Playgroud)
谢谢...
我对何时使用deferred.resolve()和感到非常困惑deferred.reject()。
快速范例
var doSomething = function() {
var deferred = $.Deferred();
if ( typeof myVar === "object" ) {
// Do something with myVar - Start.
deferred.resolve();
// Do something with myVar - End.
} else {
// myVar isn't an object, but the function has finished executing
// and that's what I want to know.
// With reject() I'll be forced to use always() instead of done()
// because there'll be also a fail() method …Run Code Online (Sandbox Code Playgroud) $xy('#simpan').click(function() {
$xy('input[id="cekbok[]"]:checked').each(function() {
var data = (this.value);
var div = (this.value);
var str = window.location.href;
var res = str.replace("wp-admin/options-general.php?page=katalogu-options", "/wp-content/plugins/katalog/includes/img/loading.gif");
var loading = ('<img src="'+res+'">') ;
$xy.ajax({
type : 'POST',
url : '../wp-content/plugins/katalogunique/proses2.php',
data: {
id : (this.value)
},
success:function (data) {
$xy('#result'+div).empty();
$xy('#result'+div).append(data);
$xy('#tz'+div).remove();
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
我的函数proses2.php在循环中发送复选框值,但是当我运行这个脚本时,它将立即运行所有ajax POST调用.我想逐个运行ajax请求或等到完成,我该如何解决这个问题?
我可以用这种方式声明一个jQuery AJAX调用:
var foo = $.ajax({ ... });
但那实际上会在那时执行请求,那么,对吗?
如何在不首先执行AJAX调用的情况下声明AJAX调用,然后再调用它?就像是:
var foo = $.ajax({ ... });
// some stuff in between
foo.execute();
Run Code Online (Sandbox Code Playgroud)
谢谢.
编辑 更多信息:我真正想做的是有一个函数,它根据参数构造一个AJAX请求,将它返回给调用代码,并让调用代码管理它的状态(即能够执行它,中止它,等等.).因此,我不想简单地声明AJAX调用的设置,而是希望获得$ .ajax返回的实际XHR对象,只有能够执行它,中止它等等.