我有以下示例 JS 代码:
function loadData(url, data) {
return $.get(url, data ? data : {});
}
function example1() {
showSpinner();
$.when(loadData('/example1', { hello: 'world' }))
.then(function (resp) {
// do something with the data
})
.always(function(){
hideSpinner();
})
.fail(function (jqXHR, textStatus, errorThrown) {
handleError(jqXHR);
});
}
function example2() {
showSpinner();
$.when(loadData('/example2', { hello: 'world' }))
.then(function (resp) {
// do something with the data
})
.then(function () {
// do something else
})
.always(function(){
hideSpinner();
})
.fail(function (jqXHR, textStatus, errorThrown) {
handleError(jqXHR);
});
}
example1()
和 example2()
使用相同的 promise 逻辑并将对返回的数据做一些不同的事情,然后总是隐藏微调器并处理失败相同(如果有的话)。问题是,在每个示例中加载数据后,我可能想做不同的事情,并且后面有多个 then's
。
但是我不得不重复always
和fail
代码。我怎样才能让它们更干所以它们只写一次但在两种情况下都使用(如果需要的话还有其他例子)。 所以我不能只是将 when 移动到一个方法中并传递一个回调,因为可能有多个回调并且在不同的 then 中。 所以这是行不通的:
function customPromise(load, callback) {
showSpinner();
$.when(load)
.then(function (resp) {
callback(resp);
})
.always(function(){
hideSpinner();
})
.fail(function (jqXHR, textStatus, errorThrown) {
handleError(jqXHR);
});
}
function example3() {
customPromise(loadData('/example2', { hello: 'world' }));
}
最佳答案
如果你有连续且未知数量的回调,我建议你将整个处理移动到创建的函数:
function handleRequest(url, data, errorCallback) {
// create promise
let promise = $.get(url, data ? data : {});
// if callback functions provided as args, chain them in `then()` calls
if (arguments.length > 3) {
let callbacks = Array.slice.call(arguments, 3);
let fn = (results) => (results);
let callback;
for (let i = 0; i < callbacks.length; i++) {
callback = callbacks[i] instanceof Function ? callbacks[i] : fn;
promise.then(callback);
}
}
// handle static behavior
promise.always(() => {
hideSpinner();
})
.fail(errorCallback);
// return the created promise
return promise;
}
您现在可以按如下方式使用此功能:
handleRequest(
'/example',
{},
(jqXHR, textStatus, errorThrown) => {
handleError(jqXHR);
},
(resp) => {
// do something with the data
},
() => {
// do something else
}
);
关于javascript - DRY Then and Always in jQuery Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47283810/