我被告知这个函数(或者一个非常相似的函数)是延迟反模式的一个例子
function writeFile(file)
{
return new WinJS.Promise(function (complete, error, progress) {
if (file) {
Windows.Storage.FileIO.writeTextAsync(file, getEditorContent()).done(
function () {
currentFile = file;
WinJS.log && WinJS.log("writeFile: file written: " + file.name + "", "MyApp", "info");
complete();
},
function (error) {
WinJS.log && WinJS.log("writeFile: error writing File " + file.name + "", "MyApp", "error");
error();
}
);
}
else {
WinJS.log && WinJS.log("writeFile: error writing File: file object was null", "MyApp", "error");
error();
}
});
}
我需要这三个分支来返回一个promise,因为这个方法是promise链的一部分。如果我想避免可怕的反模式,我应该这样做:
function writeFile(file)
{
if (file) {
return Windows.Storage.FileIO.writeTextAsync(file, getEditorContent());
}
else {
WinJS.log && WinJS.log("writeFile: error writing File: file object was null", "MyApp", "error");
return WinJS.Promise.as();
}
}
将我的done()
代码移动到调用函数。但是,writeFile
是从我的应用中的多个位置调用的,因此为了DRY的利益,在writeTextAsync
之后执行一些功能。我不想将它们移动到调用函数,所以我就这样做了。
function writeFile(file)
{
if (file) {
Windows.Storage.FileIO.writeTextAsync(file, getEditorContent()).done(
function () {
currentFile = file;
WinJS.log && WinJS.log("writeFile: file written: " + file.name + "", "MyApp", "info");
return WinJS.Promise.as();
},
function (error) {
WinJS.log && WinJS.log("writeFile: error writing File " + file.name + "", "MyApp", "error");
return WinJS.Promise.as();
}
);
}
else {
WinJS.log && WinJS.log("writeFile: error writing File: file object was null", "MyApp", "error");
return WinJS.Promise.as();
}
}
好像我刚刚交换了三张退回的承诺。这怎么样或为何更好?
我想我刚刚意识到我可以返回then
承诺writeTextAsync
返回:
function writeFile(file)
{
if (file) {
// I can return this, right?
return Windows.Storage.FileIO.writeTextAsync(file, getEditorContent()).then(
function () {
currentFile = file;
WinJS.log && WinJS.log("writeFile: file written: " + file.name + "", "MyApp", "info");
},
function (error) {
WinJS.log && WinJS.log("writeFile: error writing File " + file.name + "", "MyApp", "error");
return WinJS.Promise.wrapError(error)
}
);
}
else {
WinJS.log && WinJS.log("writeFile: error writing File: file object was null", "MyApp", "error");
return WinJS.Promise.wrapError("error writing File: file object was null")
}
}