例如在使用异步回调时节点中的文件API或Cordova中带有回调的本机函数,您将获得具有很多嵌套函数定义和参数列表的代码,这些嵌套函数定义和参数列表跨越多行,因此很难阅读。
示例:通过HTTP获取文件,并将其写入https://cordova.apache.org/blog/2017/10/18/from-filetransfer-to-xhr2.html中的cordova中的本地文件
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
console.log('file system open: ' + fs.name);
fs.root.getFile('bot.png', { create: true, exclusive: false }, function (fileEntry) {
console.log('fileEntry is file? ' + fileEntry.isFile.toString());
var oReq = new XMLHttpRequest();
// Make sure you add the domain name to the Content-Security-Policy <meta> element.
oReq.open("GET", "http://cordova.apache.org/static/img/cordova_bot.png", true);
// Define how you want the XHR data to come back
oReq.responseType = "blob";
oReq.onload = function (oEvent) {
var blob = oReq.response; // Note: not oReq.responseText
if (blob) {
// Create a URL based on the blob, and set an <img> tag's src to it.
var url = window.URL.createObjectURL(blob);
document.getElementById('bot-img').src = url;
// Or read the data with a FileReader
var reader = new FileReader();
reader.addEventListener("loadend", function() {
// reader.result contains the contents of blob as text
// this could in fact contain even more function definitions
});
reader.readAsText(blob);
} else console.error('we didnt get an XHR response!');
};
oReq.send(null);
}, function (err) { console.error('error getting file! ' + err); });
}, function (err) { console.error('error getting persistent fs! ' + err); });
这些是4个嵌套函数定义。而且,更难读的是-如何检测哪个错误处理程序属于哪个函数调用。
有人知道更清晰的写方法吗?有最佳实践模式吗?