jQuery - .always() 回调触发得太早
jQuery - .always() callback firing too soon
我正在开发一个客户端 JS 应用程序,它应该读取 CSV 文件,每行进行几次 API 调用,然后将结果写回 CSV。我坚持的部分是如何编排请求并在所有请求完成后触发一个函数。这是我目前所拥有的:
var requests = [];
// loop through rows
addresses.forEach(function (address, i) {
// make request
var addressRequest = $.ajax({
dataType: 'json',
url: 'http://api.com/addresses/' + address,
success: function (data, textStatus, jqXhr) { APP.didGetAddressJson(data, i, jqXhr) },
error: function (jqXhr, textStatus, errorThrown) { APP.didFailToGetAddressJson(errorThrown, i) },
});
requests.push(addressRequest);
// make some more requests (handled by other success functions)
});
// leggo
$.when.apply($, requests).done(APP.didFinishGeocoding);
问题是,如果其中一行抛出 404,则不会调用 done
函数。我将它切换为 always
,现在它被调用了,但不是在最后——如果我将每个回调的执行记录到控制台,它通常在中间的某个地方。但是,如果我编辑 CSV 以便没有错误,它会按预期在最后被调用。我在这里做的事情允许 always
提前触发吗?
更新: 难道只是控制台记录了它 out of order?
您需要防止错误将 $.when.apply($, requests)
编辑的承诺 return 发送到错误路径。
这可以通过以下方式实现:
- 将
.then()
链接到您的 $.ajax()
调用,而不是将 "success" 和 "error" 处理程序指定为 $.ajax()
选项。
- 通过转换为成功来处理错误(因为这是 jQuery,您必须 return 来自错误处理程序的已解决承诺)。
这种方法还允许您控制最终传送到 APP.didFinishGeocoding()
的数据
根据一些假设,您的代码的大致结构应如下所示:
function foo () {//assume there's an outer function wrapper
var errorMarker = '**error**';
var requests = addresses.map(function (address, i) {
return $.ajax({
dataType: 'json',
url: 'http://api.com/addresses/' + address
}).then(function (data, textStatus, jqXhr) { //success handler
return APP.didGetAddressJson(data, i, jqXhr); //whatever APP.didGetAddressJson() returns will appear as a result at the next stage.
}, function (jqXhr, textStatus, errorThrown) { // error handler
APP.didFailToGetAddressJson(errorThrown, i);
return $.when(errorMarker);//errorMarker will appear as a result at the next stage - but can be filtered out.
});
// make some more requests (handled by other success functions)
});
return $.when.apply($, requests).then(function() {
//first, convert arguments to an array and filter out the errors
var results = Array.prototype.slice.call(arguments).filter(function(r) {
return r !== errorMarker;
});
//then call APP.didFinishGeocoding() with the filtered results as individual arguments.
return APP.didFinishGeocoding.apply(APP, results);
//alternatively, call APP.didFinishGeocoding() with the filtered results as an array.
//return APP.didFinishGeocoding(results);
});
}
根据需要进行调整。
尝试通过 whenAll
函数传递已解决、已拒绝的 jQuery 承诺对象,在 whenAll
完成时在 .then()
中过滤已解决、已拒绝的承诺对象。另见
(function ($) {
$.when.all = whenAll;
function whenAll(arr) {
"use strict";
var deferred = new $.Deferred(),
args = !! arr
? $.isArray(arr)
? arr
: Array.prototype.slice.call(arguments)
.map(function (p) {
return p.hasOwnProperty("promise")
? p
: new $.Deferred()
.resolve(p, null, deferred.promise())
})
: [deferred.resolve(deferred.promise())],
promises = {
"success": [],
"error": []
}, doneCallback = function (res) {
promises[this.state() === "resolved"
|| res.textStatus === "success"
? "success"
: "error"].push(res);
return (promises.success.length
+ promises.error.length) === args.length
? deferred.resolve(promises)
: res
}, failCallback = function (res) {
// do `error` notification , processing stuff
// console.log(res.textStatus);
promises[this.state() === "rejected"
|| res.textStatus === "error"
? "error"
: "success"].push(res);
return (promises.success.length
+ promises.error.length) === args.length
? deferred.resolve(promises)
: res
};
$.map(args, function (promise, index) {
return $.when(promise).always(function (data, textStatus, jqxhr) {
return (textStatus === "success")
? doneCallback.call(jqxhr, {
data: data,
textStatus: textStatus
? textStatus
: jqxhr.state() === "resolved"
? "success"
: "error",
jqxhr: jqxhr
})
: failCallback.call(data, {
data: data,
textStatus: textStatus,
jqxhr: jqxhr
})
})
});
return deferred.promise()
};
}(jQuery));
例如
var request = function (url) {
return $.ajax({
url: "http://api.com/addresses/" + url,
dataType: "json"
})
}
, addresses = [
["/echo/json/"], // `success`
["/echo/jsons/"], // `error`
["/echo/json/"], // `success`
["/echo/jsons/"], // `error`
["/echo/json/"] // `success`
];
$.when.all(
$.map(addresses, function (address) {
return request(address)
})
)
.then(function (data) {
console.log(data);
// filter , process responses
$.each(data, function(key, value) {
if (key === "success") {
value.forEach(function(success, i) {
console.log(success, i);
APP.didGetAddressJson(success.data, i, success.jqxhr);
})
} else {
value.forEach(function(error, i) {
console.log(error, i);
APP.didFailToGetAddressJson(error.jqxhr, i)
})
}
})
}, function (e) {
console.log("error", e)
});
我正在开发一个客户端 JS 应用程序,它应该读取 CSV 文件,每行进行几次 API 调用,然后将结果写回 CSV。我坚持的部分是如何编排请求并在所有请求完成后触发一个函数。这是我目前所拥有的:
var requests = [];
// loop through rows
addresses.forEach(function (address, i) {
// make request
var addressRequest = $.ajax({
dataType: 'json',
url: 'http://api.com/addresses/' + address,
success: function (data, textStatus, jqXhr) { APP.didGetAddressJson(data, i, jqXhr) },
error: function (jqXhr, textStatus, errorThrown) { APP.didFailToGetAddressJson(errorThrown, i) },
});
requests.push(addressRequest);
// make some more requests (handled by other success functions)
});
// leggo
$.when.apply($, requests).done(APP.didFinishGeocoding);
问题是,如果其中一行抛出 404,则不会调用 done
函数。我将它切换为 always
,现在它被调用了,但不是在最后——如果我将每个回调的执行记录到控制台,它通常在中间的某个地方。但是,如果我编辑 CSV 以便没有错误,它会按预期在最后被调用。我在这里做的事情允许 always
提前触发吗?
更新: 难道只是控制台记录了它 out of order?
您需要防止错误将 $.when.apply($, requests)
编辑的承诺 return 发送到错误路径。
这可以通过以下方式实现:
- 将
.then()
链接到您的$.ajax()
调用,而不是将 "success" 和 "error" 处理程序指定为$.ajax()
选项。 - 通过转换为成功来处理错误(因为这是 jQuery,您必须 return 来自错误处理程序的已解决承诺)。
这种方法还允许您控制最终传送到 APP.didFinishGeocoding()
根据一些假设,您的代码的大致结构应如下所示:
function foo () {//assume there's an outer function wrapper
var errorMarker = '**error**';
var requests = addresses.map(function (address, i) {
return $.ajax({
dataType: 'json',
url: 'http://api.com/addresses/' + address
}).then(function (data, textStatus, jqXhr) { //success handler
return APP.didGetAddressJson(data, i, jqXhr); //whatever APP.didGetAddressJson() returns will appear as a result at the next stage.
}, function (jqXhr, textStatus, errorThrown) { // error handler
APP.didFailToGetAddressJson(errorThrown, i);
return $.when(errorMarker);//errorMarker will appear as a result at the next stage - but can be filtered out.
});
// make some more requests (handled by other success functions)
});
return $.when.apply($, requests).then(function() {
//first, convert arguments to an array and filter out the errors
var results = Array.prototype.slice.call(arguments).filter(function(r) {
return r !== errorMarker;
});
//then call APP.didFinishGeocoding() with the filtered results as individual arguments.
return APP.didFinishGeocoding.apply(APP, results);
//alternatively, call APP.didFinishGeocoding() with the filtered results as an array.
//return APP.didFinishGeocoding(results);
});
}
根据需要进行调整。
尝试通过 whenAll
函数传递已解决、已拒绝的 jQuery 承诺对象,在 whenAll
完成时在 .then()
中过滤已解决、已拒绝的承诺对象。另见
(function ($) {
$.when.all = whenAll;
function whenAll(arr) {
"use strict";
var deferred = new $.Deferred(),
args = !! arr
? $.isArray(arr)
? arr
: Array.prototype.slice.call(arguments)
.map(function (p) {
return p.hasOwnProperty("promise")
? p
: new $.Deferred()
.resolve(p, null, deferred.promise())
})
: [deferred.resolve(deferred.promise())],
promises = {
"success": [],
"error": []
}, doneCallback = function (res) {
promises[this.state() === "resolved"
|| res.textStatus === "success"
? "success"
: "error"].push(res);
return (promises.success.length
+ promises.error.length) === args.length
? deferred.resolve(promises)
: res
}, failCallback = function (res) {
// do `error` notification , processing stuff
// console.log(res.textStatus);
promises[this.state() === "rejected"
|| res.textStatus === "error"
? "error"
: "success"].push(res);
return (promises.success.length
+ promises.error.length) === args.length
? deferred.resolve(promises)
: res
};
$.map(args, function (promise, index) {
return $.when(promise).always(function (data, textStatus, jqxhr) {
return (textStatus === "success")
? doneCallback.call(jqxhr, {
data: data,
textStatus: textStatus
? textStatus
: jqxhr.state() === "resolved"
? "success"
: "error",
jqxhr: jqxhr
})
: failCallback.call(data, {
data: data,
textStatus: textStatus,
jqxhr: jqxhr
})
})
});
return deferred.promise()
};
}(jQuery));
例如
var request = function (url) {
return $.ajax({
url: "http://api.com/addresses/" + url,
dataType: "json"
})
}
, addresses = [
["/echo/json/"], // `success`
["/echo/jsons/"], // `error`
["/echo/json/"], // `success`
["/echo/jsons/"], // `error`
["/echo/json/"] // `success`
];
$.when.all(
$.map(addresses, function (address) {
return request(address)
})
)
.then(function (data) {
console.log(data);
// filter , process responses
$.each(data, function(key, value) {
if (key === "success") {
value.forEach(function(success, i) {
console.log(success, i);
APP.didGetAddressJson(success.data, i, success.jqxhr);
})
} else {
value.forEach(function(error, i) {
console.log(error, i);
APP.didFailToGetAddressJson(error.jqxhr, i)
})
}
})
}, function (e) {
console.log("error", e)
});