| 
                         如你所见,这让人困惑,也很难理解里面发生了什么。如果有错误出现,都很难找到并修复它们。如何改进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函数格式化并返回该列表。然后输出列表。
 
 
如你所见,每个功能只负责做一件事。 
                        (编辑:91站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |