如你所见,这让人狐疑,也很难领略内里产生了什么。假若有错误呈现,都很难找到并修复它们。怎样改造startProgram函数?可以将民众逻辑提取到函数中。以下是详细操纵要领:
- function startProgram() {
- if (!window.indexedDB) {
- throw new Error("Browser doesn't support indexedDB");
- }
-
- initDatabase();
- setListeners();
- printEmployeeList();
- }
-
- function initDatabase() {
- let openRequest = indexedDB.open('store', 1);
-
- openRequest.onerror = () => {
- console.error('Error', openRequest.error);
- };
- openRequest.onsuccess = () => {
- let db = openRequest.result;
- };
- }
-
- function setListeners() {
- document.getElementById('stat-op').addEventListener('click', () => {});
- document.getElementById('pre2456').addEventListener('click', () => {});
- document.getElementById('cpTagList100').addEventListener('change', () => {});
- document.getElementById('cpTagList101').addEventListener('click', () => {});
- document.getElementById('gototop').addEventListener('click', () => {});
- document.getElementById('asp10').addEventListener('click', () => {});
- }
-
- async function printEmployeeList() {
- const employees = await getEmployeeList();
-
- document.getElementById('employeeSelect').innerHTML = formatEmployeeList(employees);
- }
-
- function formatEmployeeList(employees) {
- return employees.reduce(
- (content, employee) => content + employee.name + '<br>',
- ''
- );
- }
-
- function getEmployeeList() {
- return fetch('employeeList.json').then(res => res.json());
- }
把逻辑提取到函数里
细心看看startProgram函数的变革:
- 起首,通过行使一个卫语句替代掉if-else语句。然后,启动数据库所需的逻辑提取到initDatabase函数中,并将变乱侦听器添加到setListeners函数中。
- 打印员工列表的逻辑轻微伟大一些,因此建设了三个函数:printEmployeeList, formatEmployeeList和getEmployeeList。
- getEmployeeList认真向employeeList.json发出GET哀求并以json名目返反相应。
- 然后由printEmployeeList函数挪用getEmployeeList,该函数获取员工列表并将其转达给formatEmployeeList函数,formatEmployeeList函数名目化并返回该列表。然后输出列表。
如你所见,每个成果只认真做一件事。
(编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|