使用 Promise 构建高度交互的 UI 给我带来了很多乐趣。然而,我遇到了一个棘手的情况。我有一个返回执行服务器更新的 promise 的函数。我想使用后续的 promise 处理程序来更新客户端模型,然后向 UI 发出更新事件。这是我的代码:
function updateServer (action) {
return $.post(URL, { action: action })
.fail(function (error) {
console.log(error);
});
}
// An example action that might affect the server
_this.freeze = function (mode) {
updateServer("freeze").done(function (data) {
_this.model.data.status = data.status;
})
.done(function () {
$(window).trigger(Events.UpdateUI);
});
};
您会注意到我必须在卡住命令中发出更新事件。我更愿意在 updateServer 函数内执行此操作,以避免在每个控制方法中重复代码。
我想出了一种方法,通过将模型更新函数作为参数传递给 updateServer,但是,这似乎违反了我认为的 promise 精神:
function updateServer (action, fn) {
return $.post(URL, { action: action })
.done(fn)
.done(function () {
$(window).trigger(Events.UpdateUI);
})
.fail(function (error) {
console.log(error);
});
}
// An example action that might affect the server
_this.freeze = function (mode) {
updateServer("freeze", function (data) {
_this.model.data.status = data.status;
});
};
我认为另一种方法是设计某种优先级较低的完成处理程序,这样我就能保持 promise 可堆肥性的精神。我是否遗漏了什么,或者我是否以“正确的方式”这样做?
谢谢大家!
最佳答案
我认为您会想要使用一个辅助函数来包装您的整个操作:
function updateUIwith(result) {
return result.then(function() {
$(window).trigger(Events.UpdateUI);
}).fail(function(error) {
console.log(error);
});
}
现在你只需要写
function updateServer(action) {
return $.post(URL, {action: action})
}
// An example action that might affect the server
_this.freeze = function(mode) {
updateUIwith(updateServer("freeze").then(function(data) {
_this.model.data.status = data.status;
}));
};
关于javascript - 控制 Promise 执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28906875/