前言 在完成了鸿小易以及NowInOpenHarmony这两个项目的开发之后我们,子安学长将我引荐给了陈若愚老师,陈老师联系到中软国际,想要让我们去开发应用并协助我们将应用上架,这对于我来说可谓是千载难逢的机会了,毕竟我一直渴望能真正上架一个应用,但一致被后端服务器,备案,资质,内容过于简单等等一系列的问题所卡住,这次有了中软的协助我们应该就能更加专注于开发了。
而且这一次,我不再是独立开发,而是有了孙妈以及bqf,zxjc,hyx的协作,五个人的力量,再加上Codex,Claude Code的协助我相信我们一定能成功上架的。
选题 中软的老师确实是给了我们很多可选的选题,都是很标准的两个主功能的小应用,很轻量化,但也确实是没什么实际用途做出来也只是在应用市场上充数罢了,所以不如说是去圆一下之前的梦,把鸿小易和NowInOpenHarmony这两个应用给融合为一个新应用,于是“鸿易讯”诞生了。
核心功能
功能层级
功能名称
子功能/具体内容
说明
一级功能
鸿蒙新闻资讯
二级功能1:鸿蒙新闻
展示鸿蒙系统相关的最新行业新闻、官方动态、技术更新等内容
二级功能2:开源鸿蒙新闻
聚焦开源鸿蒙项目的进展、社区动态、代码提交、开源合作等信息
一级功能
鸿蒙智能问答AI助手
二级功能1:快速问答模式
针对鸿蒙开发相关的基础问题、常见疑问,提供快速精准的解答
二级功能2:DeepResearch模式
针对复杂的鸿蒙开发技术难题、深度研究需求,进行多维度分析与详细解答
一级功能
设置
隐私政策
展示应用数据收集、使用、存储及保护相关的隐私条款内容
版本号
显示当前应用的版本信息(示例:V1.0.0)
核心问题记录 这一次我不准备再像过去一样事无巨细的去记录全部流程,而是只去分析记录核心问题的解决方案以及一些试错方案,并且对于AI生成的代码去进行更进一步的解读。
AppInit 在我开发NowInOpenHarmony的时候,我参考子安学长曾经项目中的模式,将全部需要进行初始化的模块功能统一封装到了Product模块的AppInit类中,这也是可以针对于不同形态的设备配置不同的AppInit流程。这一块我此前并没有很多实践经验,对于具体的初始化流程规划以及日志的打印格式都是以实用主义的模式去进行编写的,一切以能排查出Bug为目标,就没有很规范。所以我决定要用AI去帮我进行一下重构。
在此前的经验中我们可以知道Claude对于ArkTS的开发有一定的基础认知但是对于接口的版本以及TS于ArkTS的语法临界区没有很好的把握,所以我选择使用详尽的描述以及在现有代码结构上举例说明的形式,来让Claude把其他应用开发中的通识性经验迁移到我的项目中,我也可以趁机学习一下对于多Promise的管理以及对于日志的格式化输出。
首先我先放一下在NowInOpenHarmony中AppInit的代码作为对比。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 import { GET_USER_CONFIG , logger, preferenceDB, UserConfigViewModel } from "common" ; import { common } from "@kit.AbilityKit" ;import { AppStorageV2 , promptAction } from "@kit.ArkUI" ;import { colorModManager, newsManager, userConfigManager } from "feature" ;import { lvCode, lvText } from "@luvi/lv-markdown-in" ;const AppInit _LOG_TAG = 'AppInit: ' export class AppInit { configInit (context : common.UIAbilityContext ) { const isPreferenceDBInitSuccess : boolean = preferenceDB.init (context) if (isPreferenceDBInitSuccess) { logger.info (`${AppInit_LOG_TAG} 首选项数据对象初始化成功` ) if (userConfigManager.syncDataToAppStorage ()) { return true } return false } else { promptAction.openToast ({ message : `${AppInit_LOG_TAG} 首选项数据对象初始化错误` }) logger.error (`${AppInit_LOG_TAG} 首选项数据对象初始化错误` ) return false } } async initAll (uiAbilityContext : common.UIAbilityContext , applicationContext : common.ApplicationContext ) { await newsManager.init (uiAbilityContext) this .configInit (uiAbilityContext) colorModManager.init (applicationContext) await newsManager.updateNewsListToDB () await newsManager.updateNewsSwiperToDB () } markDownConfigInit ( ) { let baseFontSize = AppStorageV2 .connect (UserConfigViewModel , GET_USER_CONFIG , () => new UserConfigViewModel ())!.fontSize lvCode.setIndexState (true ) lvText.setTextSize (baseFontSize) logger.info (`${AppInit_LOG_TAG} Markdown初始化成功` ) } } export const appInit = new AppInit ()
我原本的手搓版本只是在一位的滥用await去进行异步的处理,并没用到很多Promise原生的对于多异步任务的管理方法。
接下来让我们来看一下Claude给出的版本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 import { APP_STORAGE_KEYS , logger, preferenceDB, UserConfigViewModel , LOG_TAG , kvDatabase } from "common" ; import { common } from "@kit.AbilityKit" ;import { colorModManager, newsManager, userConfigManager } from "feature" ;import { AppStorageV2 , promptAction } from "@kit.ArkUI" ;import { lvCode, lvText } from "@luvi/lv-markdown-in" ;import { InitStatus } from "../modules/AppInit/InitStatus" ;export class AppInit { private initStatus : InitStatus = { databases : false , userConfig : false , managers : false , appStorageV2 : false , markdown : false } async initPhase1_BaseModules (uiAbilityContext : common.UIAbilityContext ): Promise <boolean > { logger.info (`${LOG_TAG.APP_INIT} ========== 开始阶段 1:基础模块初始化 ==========` ) try { logger.info (`${LOG_TAG.APP_INIT} 步骤 1/4:初始化数据库模块...` ) const dbInitSuccess = await this .initDatabases (uiAbilityContext) if (!dbInitSuccess) { logger.error (`${LOG_TAG.APP_INIT} ✗ 数据库初始化失败,终止初始化流程 - 请检查应用权限和存储空间` ) return false } logger.info (`${LOG_TAG.APP_INIT} 步骤 2/4:加载用户配置...` ) const configInitSuccess = this .initUserConfig (uiAbilityContext) if (!configInitSuccess) { logger.warn (`${LOG_TAG.APP_INIT} 用户配置初始化失败,将使用默认配置` ) } logger.info (`${LOG_TAG.APP_INIT} 步骤 3/4:初始化业务管理器...` ) const managersInitSuccess = await this .initManagers (uiAbilityContext) if (!managersInitSuccess) { logger.error (`${LOG_TAG.APP_INIT} ✗ 管理器初始化失败 - 应用可继续运行但新闻功能不可用` ) } logger.info (`${LOG_TAG.APP_INIT} 步骤 4/4:预加载应用数据...` ) await this .preloadData () logger.info (`${LOG_TAG.APP_INIT} ========== 阶段 1 完成:基础模块初始化成功 ==========` ) return true } catch (error) { logger.error (`${LOG_TAG.APP_INIT} ✗ 阶段 1 初始化异常 - 详细信息:${JSON .stringify(error)} ` ) promptAction.openToast ({ message : '应用初始化失败,请重启应用' }) return false } } private async initDatabases (context : common.UIAbilityContext ): Promise <boolean > { const kvInitSuccess = kvDatabase.init (context) if (kvInitSuccess) { logger.info (`${LOG_TAG.APP_INIT} ✓ KV 数据库初始化成功` ) this .initStatus .databases = true } else { logger.error (`${LOG_TAG.APP_INIT} ✗ KV 数据库初始化失败 - 原因:KVManager 创建失败或 context 无效` ) return false } const preferenceInitSuccess = preferenceDB.init (context) if (preferenceInitSuccess) { logger.info (`${LOG_TAG.APP_INIT} ✓ 偏好设置数据库初始化成功` ) } else { logger.error (`${LOG_TAG.APP_INIT} ✗ 偏好设置数据库初始化失败 - 原因:Preferences 实例创建失败` ) return false } return true } private initUserConfig (context : common.UIAbilityContext ): boolean { try { const syncSuccess = userConfigManager.syncDataToAppStorage () if (syncSuccess) { logger.info (`${LOG_TAG.APP_INIT} ✓ 用户配置加载成功` ) this .initStatus .userConfig = true return true } else { logger.warn (`${LOG_TAG.APP_INIT} ⚠ 用户配置加载失败 - 原因:PreferenceDB 数据读取失败,将使用默认配置` ) return false } } catch (error) { logger.error (`${LOG_TAG.APP_INIT} ✗ 用户配置加载异常 - 原因:${JSON .stringify(error)} ` ) return false } } private async initManagers (context : common.UIAbilityContext ): Promise <boolean > { try { const newsManagerInitSuccess = await newsManager.init (context) if (newsManagerInitSuccess) { logger.info (`${LOG_TAG.APP_INIT} ✓ 新闻管理器初始化成功` ) this .initStatus .managers = true return true } else { logger.error (`${LOG_TAG.APP_INIT} ✗ 新闻管理器初始化失败 - 原因:无法获取 KV 数据库实例` ) return false } } catch (error) { logger.error (`${LOG_TAG.APP_INIT} ✗ 管理器初始化异常 - 原因:${JSON .stringify(error)} ` ) return false } } private async preloadData (): Promise <void > { try { Promise .all ([ newsManager.updateNewsListToDB (), newsManager.updateNewsSwiperToDB () ]).then (() => { logger.info (`${LOG_TAG.APP_INIT} 数据预加载完成` ) }).catch ((error : Error ) => { logger.warn (`${LOG_TAG.APP_INIT} 数据预加载失败: ${JSON .stringify(error)} ,将使用缓存数据` ) }) } catch (error) { logger.warn (`${LOG_TAG.APP_INIT} 数据预加载异常: ${JSON .stringify(error)} ` ) } } initPhase2_WindowRelated (applicationContext : common.ApplicationContext ): boolean { logger.info (`${LOG_TAG.APP_INIT} ========== 开始阶段 2:窗口相关初始化 ==========` ) try { logger.info (`${LOG_TAG.APP_INIT} 初始化颜色模式管理器...` ) const colorModInitSuccess = colorModManager.init (applicationContext) if (colorModInitSuccess) { logger.info (`${LOG_TAG.APP_INIT} ✓ 颜色模式管理器初始化成功` ) this .initStatus .appStorageV2 = true } else { logger.warn (`${LOG_TAG.APP_INIT} ⚠ 颜色模式管理器初始化失败 - 原因:ApplicationContext 无效,将使用默认主题` ) } logger.info (`${LOG_TAG.APP_INIT} ========== 阶段 2 完成:窗口相关初始化成功 ==========` ) return true } catch (error) { logger.error (`${LOG_TAG.APP_INIT} 阶段 2 初始化异常: ${JSON .stringify(error)} ` ) return false } } initPhase3_UIDependent (): boolean { logger.info (`${LOG_TAG.APP_INIT} ========== 开始阶段 3:UI 依赖模块初始化 ==========` ) try { logger.info (`${LOG_TAG.APP_INIT} 初始化 Markdown 配置...` ) const markdownInitSuccess = this .markDownConfigInit () if (markdownInitSuccess) { logger.info (`${LOG_TAG.APP_INIT} ✓ Markdown 配置初始化成功` ) } else { logger.warn (`${LOG_TAG.APP_INIT} ⚠ Markdown 配置初始化失败 - 原因:无法从 AppStorageV2 获取用户配置,将使用默认配置` ) } logger.info (`${LOG_TAG.APP_INIT} ========== 阶段 3 完成:UI 依赖模块初始化成功 ==========` ) return true } catch (error) { logger.error (`${LOG_TAG.APP_INIT} 阶段 3 初始化异常: ${JSON .stringify(error)} ` ) return false } } markDownConfigInit (): boolean { try { const userConfig = AppStorageV2 .connect ( UserConfigViewModel , APP_STORAGE_KEYS .USER_CONFIG , () => new UserConfigViewModel () ) if (!userConfig) { logger.error (`${LOG_TAG.APP_INIT} ✗ 无法获取用户配置 - 原因:AppStorageV2 中不存在 USER_CONFIG,Markdown 使用默认字体大小` ) return false } const baseFontSize = userConfig.fontSize lvCode.setIndexState (true ) lvText.setTextSize (baseFontSize) logger.info (`${LOG_TAG.APP_INIT} ✓ Markdown 配置成功,字体大小: ${baseFontSize} ` ) this .initStatus .markdown = true return true } catch (error) { logger.error (`${LOG_TAG.APP_INIT} ✗ Markdown 配置异常 - 原因:${JSON .stringify(error)} ` ) return false } } printInitStatus (): void { logger.info (`${LOG_TAG.APP_INIT} ========== 初始化状态报告 ==========` ) if (this .initStatus .databases ) { logger.info (`${LOG_TAG.APP_INIT} [数据库模块] ✓ 初始化成功` ) } else { logger.warn (`${LOG_TAG.APP_INIT} [数据库模块] ✗ 初始化失败 - 影响:离线功能可能不可用` ) } if (this .initStatus .userConfig ) { logger.info (`${LOG_TAG.APP_INIT} [用户配置] ✓ 初始化成功` ) } else { logger.warn (`${LOG_TAG.APP_INIT} [用户配置] ✗ 初始化失败 - 影响:将使用默认配置(字体16、跟随系统主题)` ) } if (this .initStatus .managers ) { logger.info (`${LOG_TAG.APP_INIT} [业务管理器] ✓ 初始化成功` ) } else { logger.warn (`${LOG_TAG.APP_INIT} [业务管理器] ✗ 初始化失败 - 影响:新闻数据功能不可用,请检查网络或数据库` ) } if (this .initStatus .appStorageV2 ) { logger.info (`${LOG_TAG.APP_INIT} [AppStorageV2] ✓ 初始化成功` ) } else { logger.warn (`${LOG_TAG.APP_INIT} [AppStorageV2] ✗ 初始化失败 - 影响:主题切换功能可能不可用` ) } if (this .initStatus .markdown ) { logger.info (`${LOG_TAG.APP_INIT} [Markdown配置] ✓ 初始化成功` ) } else { logger.warn (`${LOG_TAG.APP_INIT} [Markdown配置] ✗ 初始化失败 - 影响:文章渲染使用默认字体` ) } logger.info (`${LOG_TAG.APP_INIT} ======================================` ) } getInitStatus (): InitStatus { return { databases : this .initStatus .databases , userConfig : this .initStatus .userConfig , managers : this .initStatus .managers , appStorageV2 : this .initStatus .appStorageV2 , markdown : this .initStatus .markdown } } isFullyInitialized (): boolean { return this .initStatus .databases && this .initStatus .userConfig && this .initStatus .managers && this .initStatus .appStorageV2 && this .initStatus .markdown } } export const appInit = new AppInit ()
上面是新版的全部源码,由于这一次我是带着学习的心态去编写代码的,所以我让Claude给出了较为详细的注释也方便我们学习。接下来让我们分段拆解一下这个代码。
分段初始化 首先Claude对于整体初始化的流程进行了阶段的划分,它将初始化的过程切分成了三个阶段,分别是:
基础模块初始化
窗口相关模块初始化
UI 依赖模块初始化
这三个阶段分别对应了三个方法:
initPhase1_BaseModules()
initPhase2_WindowRelated()
initPhase3_UIDependent()
这个阶段的划分是依据于模块的依赖关系和初始化的时间点。
基础模块初始化:包括数据库、用户配置、业务管理器、AppStorageV2 和 Markdown 配置。这些模块是其他模块的基础,必须在应用启动时就初始化完成。
窗口相关模块初始化:包括窗口管理器、窗口装饰器等。这些模块依赖于基础模块,必须在窗口创建时初始化。
UI 依赖模块初始化:包括界面元素、事件处理等。这些模块依赖于窗口相关模块,必须在界面加载完成后初始化。
异步任务执行顺序管理 在我单独花了一段时间品读了一下Claude的代码之后才发现一段好的代码是真的可以赏心悦目,可以被称之为艺术品了。
这里我们需要结合着EntryAbility的代码来理解讲解。
首先我们要清楚的一点在于我们不同阶段之间以及不同阶段内部存在着一定量的彼此依存,需要严格依照正确的顺序执行,就比如说是我们的新闻数据Manager模块都要依赖于键值数据库的初始化,所有的配置数据Manager模块都依赖于用户首选项数据库的初始化。所以初始化的顺序至关重要。
而当前我们的初始化过程中包含了大量的异步任务,这些异步任务的实际执行时长各不相同,我们所需要的是利用Promise类内置的一系列静态方法来去控制多个异步任务的执行顺序,通过在上一个异步任务的then回调函数中去拉起下一个与之存在依赖关系的异步任务进入任务队列,从而实现异步任务的有序执行。这里不禁让我联想到了当初数据结构所学过的拓扑结构,只有完成全部的前置节点才能达到下一个节点,其应用真的很广,可以说是在日常生活中无处不在的了。
这里我先去放一下EntryAbility的源码然后咱们参照着源码逐一讲解。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 import { AbilityConstant , UIAbility , Want } from '@kit.AbilityKit' ;import { hilog } from '@kit.PerformanceAnalysisKit' ;import { AppStorageV2 , window } from '@kit.ArkUI' ;import { appInit } from '../init/AppInit' ;import { userConfigManager } from 'feature' ;import { APP_STORAGE_KEYS , WinWidth , logger, LOG_TAG } from 'common' ;const DOMAIN = 0x0000 ;const TAG = 'EntryAbility' ;export default class EntryAbility extends UIAbility { private phase1Promise : Promise <boolean > | null = null onCreate (want : Want , launchParam : AbilityConstant .LaunchParam ): void { hilog.info (DOMAIN , TAG , '%{public}s' , 'Ability onCreate' ); logger.info (`${LOG_TAG.ENTRY_ABILITY} 应用启动,开始初始化流程` ) this .phase1Promise = appInit.initPhase1_BaseModules (this .context ) } onDestroy (): void { hilog.info (DOMAIN , TAG , '%{public}s' , 'Ability onDestroy' ); logger.info (`${LOG_TAG.ENTRY_ABILITY} 应用销毁` ) } onWindowStageCreate (windowStage : window .WindowStage ): void { hilog.info (DOMAIN , TAG , '%{public}s' , 'Ability onWindowStageCreate' ); logger.info (`${LOG_TAG.ENTRY_ABILITY} 窗口创建,等待阶段 1 完成...` ) const phase1Promise = this .phase1Promise || Promise .resolve (false ) phase1Promise.then ((phase1Success ) => { if (phase1Success) { logger.info (`${LOG_TAG.ENTRY_ABILITY} ✓ 阶段 1 初始化成功` ) } else { logger.error (`${LOG_TAG.ENTRY_ABILITY} ✗ 阶段 1 初始化失败,应用可能无法正常运行` ) } logger.info (`${LOG_TAG.ENTRY_ABILITY} 开始阶段 2 初始化...` ) const phase2Success = appInit.initPhase2_WindowRelated (this .context .getApplicationContext ()) if (phase2Success) { logger.info (`${LOG_TAG.ENTRY_ABILITY} ✓ 阶段 2 初始化成功` ) } else { logger.warn (`${LOG_TAG.ENTRY_ABILITY} ⚠ 阶段 2 初始化失败,部分功能可能受影响` ) } window .getLastWindow (this .context ).then ((win ) => { const winWidth = win.getWindowProperties ().windowRect .width AppStorageV2 .connect (WinWidth , APP_STORAGE_KEYS .WINDOW_WIDTH , () => new WinWidth (winWidth)) logger.info (`${LOG_TAG.ENTRY_ABILITY} 窗口宽度已存储到 AppStorageV2: ${winWidth} px` ) }).catch ((error : Error ) => { logger.error (`${LOG_TAG.ENTRY_ABILITY} 获取窗口宽度失败: ${JSON .stringify(error)} ` ) }) windowStage.loadContent ('pages/StartPage' , (err ) => { if (err.code ) { hilog.error (DOMAIN , TAG , 'Failed to load the content. Cause: %{public}s' , JSON .stringify (err)); logger.error (`${LOG_TAG.ENTRY_ABILITY} 页面加载失败: ${JSON .stringify(err)} ` ) return ; } hilog.info (DOMAIN , TAG , 'Succeeded in loading the content.' ); logger.info (`${LOG_TAG.ENTRY_ABILITY} 启动页加载成功` ) logger.info (`${LOG_TAG.ENTRY_ABILITY} 开始阶段 3 初始化...` ) const phase3Success = appInit.initPhase3_UIDependent () if (phase3Success) { logger.info (`${LOG_TAG.ENTRY_ABILITY} ✓ 阶段 3 初始化成功` ) } else { logger.warn (`${LOG_TAG.ENTRY_ABILITY} ⚠ 阶段 3 初始化失败,部分功能可能受影响` ) } setTimeout (() => { this .printFinalInitStatus () }, 100 ) }); }).catch ((error : Error ) => { logger.error (`${LOG_TAG.ENTRY_ABILITY} ✗ 阶段 1 初始化异常: ${JSON .stringify(error)} ` ) logger.error (`${LOG_TAG.ENTRY_ABILITY} 应用启动失败,请重启应用` ) }) } private printFinalInitStatus (): void { logger.info (`${LOG_TAG.ENTRY_ABILITY} ========================================` ) logger.info (`${LOG_TAG.ENTRY_ABILITY} 应用初始化完成状态报告` ) logger.info (`${LOG_TAG.ENTRY_ABILITY} ========================================` ) appInit.printInitStatus () if (appInit.isFullyInitialized ()) { logger.info (`${LOG_TAG.ENTRY_ABILITY} ` ) logger.info (`${LOG_TAG.ENTRY_ABILITY} 🎉 应用完全初始化成功,所有功能可用` ) logger.info (`${LOG_TAG.ENTRY_ABILITY} ` ) } else { logger.warn (`${LOG_TAG.ENTRY_ABILITY} ` ) logger.warn (`${LOG_TAG.ENTRY_ABILITY} ⚠️ 应用初始化不完整,部分功能可能受限` ) const status = appInit.getInitStatus () logger.warn (`${LOG_TAG.ENTRY_ABILITY} 详细状态: ${JSON .stringify(status)} ` ) logger.warn (`${LOG_TAG.ENTRY_ABILITY} ` ) } logger.info (`${LOG_TAG.ENTRY_ABILITY} ========================================` ) } onWindowStageDestroy (): void { hilog.info (DOMAIN , TAG , '%{public}s' , 'Ability onWindowStageDestroy' ); logger.info (`${LOG_TAG.ENTRY_ABILITY} 窗口销毁` ) } onForeground (): void { hilog.info (DOMAIN , TAG , '%{public}s' , 'Ability onForeground' ); logger.info (`${LOG_TAG.ENTRY_ABILITY} 应用进入前台` ) } onBackground (): void { hilog.info (DOMAIN , TAG , '%{public}s' , 'Ability onBackground' ); logger.info (`${LOG_TAG.ENTRY_ABILITY} 应用进入后台,开始保存用户数据` ) const syncSuccess = userConfigManager.syncDataToPreference () if (syncSuccess) { logger.info (`${LOG_TAG.ENTRY_ABILITY} 用户配置保存成功` ) } else { logger.error (`${LOG_TAG.ENTRY_ABILITY} 用户配置保存失败,设置可能丢失` ) } } }
通过AppInit的源代码我们可以看到,我们所有的异步操作其实是全部被包裹在了initPhase1中,initPhase1是在Ability的onCreate中调用的,所以我们所有的异步操作都是在Ability的onCreate中完成的。但是问题在于后面的onWindowStageCreate窗口创建阶段与我们的onCreate函数是两个独立的代码块,彼此之间的局部变量并不互通,我们在onCreate的函数中创建的Promise实例对象无法在onWindowStageCreate中访问,所以为了保证阶段二的执行顺序,我们要将appInit.initPhase1_BaseModules对象的可见区域扩大,扩大至当前EntryAbility类的局部变量中。
1 2 3 4 5 6 7 8 private phase1Promise : Promise <boolean > | null = null
将作用域提升之后,我们在onCreate函数中去进行promise对象的启动,将启动后的对象的引用赋值给this.phase1Promise,然后在onWindowStageCreate函数中去等待这个promise对象的完成。在完成后去调用appInit.initPhase2_UI函数进行阶段二的初始化。二阶段之所以是没有被单独提升作用域,这是因为二阶段和三阶段都是同步的。三阶段会很自然的排在二阶段的后面,无需额外进行更多操作。
在三个阶段的初始化过程中,每一步的初始化成功之后都会在initStatus这个对象中去记录其初始化状态,如果成功就会在对应的键值中去记录为true,失败就会记录为false。随后在三个初始化阶段的最后会统一进行结果的输出。
而在这个过程中,可能会出现同步进程连续执行,持续到应用准备阶段的最后也没有流出空闲去处理异步函数,导致最后输出的结果为失败是因为还没有执行(在早期版本时,我们的的确确遇到了这个问题。)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 11-18 13:28:07.652 8088-8088 A00000/com.xbxy...EntryAbility apppool I Ability onCreate 11-18 13:28:07.652 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I EntryAbility: 应用启动,开始初始化流程 11-18 13:28:07.652 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I AppInit: ========== 开始阶段 1:基础模块初始化 ========== 11-18 13:28:07.652 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I AppInit: 步骤 1/4:初始化数据库模块... 11-18 13:28:07.653 8088-8088 A03D00/com.xbx...ngYiXun/JSAPP apppool I KVDatabase: Succeeded in creating KVManager. 11-18 13:28:07.653 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I KVDatabase: 数据库管理对象创建成功。 11-18 13:28:07.653 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I AppInit: ✓ KV 数据库初始化成功 11-18 13:28:07.653 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I AppInit: ✓ 偏好设置数据库初始化成功 11-18 13:28:07.653 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I AppInit: 步骤 2/4:加载用户配置... 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I PreferenceDB: Has ColorMode data: true 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool W PreferenceDB: Get data ColorMode: 0 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I UserConfigManager: 检测到COLOR_MODE = 0 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool W PreferenceDB: Get data ColorMode: 0 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I PreferenceDB: Has FontSize data: true 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool W PreferenceDB: Get data FontSize: 18 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I UserConfigManager: 检测到FONT_SIZE = 18 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool W PreferenceDB: Get data FontSize: 18 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I PreferenceDB: Has FontSize data: true 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I PreferenceDB: Has ColorMode data: true 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool W PreferenceDB: Get data ColorMode: 0 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool W PreferenceDB: Get data FontSize: 18 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool W UserConfigManager: 用户首选项持久化数据读取成功,colorMode=0,fontSize=18 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I AppInit: ✓ 用户配置加载成功 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I AppInit: 步骤 3/4:初始化业务管理器... 11-18 13:28:07.655 8088-8088 A03D00/com.xbx...ngYiXun/JSAPP apppool I KVDatabase: Succeeded in creating KVManager. 11-18 13:28:07.655 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I KVDatabase: 数据库管理对象创建成功。 11-18 13:28:07.665 8088-8088 A00000/com.xbxy...EntryAbility apppool I Ability onWindowStageCreate 11-18 13:28:07.665 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I EntryAbility: 窗口创建,开始窗口相关初始化 11-18 13:28:07.666 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I AppInit: ========== 开始阶段 2:窗口相关初始化 ========== 11-18 13:28:07.666 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I AppInit: 初始化颜色模式管理器... 11-18 13:28:07.666 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I ColorModManager: applicationContext初始化成功 11-18 13:28:07.666 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I ColorModManager: initColoModSetting 0: AppStorageV2colorModel = 0 11-18 13:28:07.666 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I AppInit: ✓ 颜色模式管理器初始化成功 11-18 13:28:07.666 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I AppInit: ========== 阶段 2 完成:窗口相关初始化成功 ========== 11-18 13:28:07.666 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I EntryAbility: 阶段 2 初始化成功 11-18 13:28:07.669 8088-8088 A00000/com.xbxy...EntryAbility apppool I Ability onForeground 11-18 13:28:07.669 8088-8088 A01234/com.xbx...Xun/XBXLogger apppool I EntryAbility: 应用进入前台 11-18 13:28:07.707 8088-8088 A00000/com.xbxy...EntryAbility com.xbxyf...ongYiXun I Succeeded in loading the content. 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I EntryAbility: 启动页加载成功 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I AppInit: ========== 开始阶段 3:UI 依赖模块初始化 ========== 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I AppInit: 初始化 Markdown 配置... 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I AppInit: ✓ Markdown 配置成功,字体大小: 18 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I AppInit: ✓ Markdown 配置初始化成功 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I AppInit: ========== 阶段 3 完成:UI 依赖模块初始化成功 ========== 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I AppInit: ========== 应用初始化全部完成 ========== 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I AppInit: ========== 初始化状态报告 ========== 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I AppInit: [数据库模块] ✓ 初始化成功 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I AppInit: [用户配置] ✓ 初始化成功 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun W AppInit: [业务管理器] ✗ 初始化失败 - 影响:新闻数据功能不可用,请检查网络或数据库 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I AppInit: [AppStorageV2] ✓ 初始化成功 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I AppInit: [Markdown配置] ✓ 初始化成功 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I AppInit: ====================================== 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I EntryAbility: 阶段 3 初始化成功 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun W EntryAbility: 应用初始化不完整,部分功能可能受限 11-18 13:28:07.707 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun W EntryAbility: 初始化状态: {"databases" :true ,"userConfig" :true ,"managers" :false ,"appStorageV2" :true ,"markdown" :true } 11-18 13:28:07.708 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I KVDatabase: 成功获取storeId:HongYiXunKVDB数据库实例对象 11-18 13:28:07.708 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I NewsManager: init: 获取appKVDb成功 11-18 13:28:07.708 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I AppInit: ✓ 新闻管理器初始化成功 11-18 13:28:07.708 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I AppInit: 步骤 4/4:预加载应用数据... 11-18 13:28:07.708 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun D AxiosHttp: 进入AxiosHttp.request URL = /api/health 11-18 13:28:07.721 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun D AxiosHttp: 进入AxiosHttp.request URL = /api/banner/status 11-18 13:28:07.722 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I AppInit: ========== 阶段 1 完成:基础模块初始化成功 ========== 11-18 13:28:07.722 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I EntryAbility: 阶段 1 初始化成功 11-18 13:28:07.723 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun I EntryAbility: 窗口宽度已存储到 AppStorageV2: 1320px 11-18 13:28:07.725 8088-8088 A01234/com.xbx...Xun/XBXLogger com.xbxyf...ongYiXun D StartPage: winWidth: 440
1 AppInit: [业务管理器] ✗ 初始化失败 - 影响:新闻数据功能不可用,请检查网络或数据库
从这一条和
1 2 AppInit: ✓ 新闻管理器初始化成功 AppInit: 步骤 4/4:预加载应用数据...
这一条的输出顺序可以看出,异步函数的执行顺序问题是确实存在的,是需要解决的问题。
所以为了程序的稳定性,我们需要手动留出一段强制空闲时间去给异步操作进行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 windowStage.loadContent ('pages/StartPage' , (err ) => { if (err.code ) { hilog.error (DOMAIN , TAG , 'Failed to load the content. Cause: %{public}s' , JSON .stringify (err)); logger.error (`${LOG_TAG.ENTRY_ABILITY} 页面加载失败: ${JSON .stringify(err)} ` ) return ; } hilog.info (DOMAIN , TAG , 'Succeeded in loading the content.' ); logger.info (`${LOG_TAG.ENTRY_ABILITY} 启动页加载成功` ) logger.info (`${LOG_TAG.ENTRY_ABILITY} 开始阶段 3 初始化...` ) const phase3Success = appInit.initPhase3_UIDependent () if (phase3Success) { logger.info (`${LOG_TAG.ENTRY_ABILITY} ✓ 阶段 3 初始化成功` ) } else { logger.warn (`${LOG_TAG.ENTRY_ABILITY} ⚠ 阶段 3 初始化失败,部分功能可能受影响` ) } setTimeout (() => { this .printFinalInitStatus () }, 100 ) });
js和ts的异步逻辑是任务队列,我们通过定时器,将打印函数的调用塞在全部异步操作塞在打印之前,强制将打印函数的执行塞到任务队列的最后。这里设置为100ms是因为在正常情况下这些操作的执行总时长应该是远远低于100ms,若是高于100ms则说明他的执行过程中大概率发生了异常。
随后,对于printFinalInitStatus,这个函数会负责统一的输出三个阶段的初始化状态报告。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 private printFinalInitStatus (): void { logger.info (`${LOG_TAG.ENTRY_ABILITY} ========================================` ) logger.info (`${LOG_TAG.ENTRY_ABILITY} 应用初始化完成状态报告` ) logger.info (`${LOG_TAG.ENTRY_ABILITY} ========================================` ) appInit.printInitStatus () if (appInit.isFullyInitialized ()) { logger.info (`${LOG_TAG.ENTRY_ABILITY} ` ) logger.info (`${LOG_TAG.ENTRY_ABILITY} 🎉 应用完全初始化成功,所有功能可用` ) logger.info (`${LOG_TAG.ENTRY_ABILITY} ` ) } else { logger.warn (`${LOG_TAG.ENTRY_ABILITY} ` ) logger.warn (`${LOG_TAG.ENTRY_ABILITY} ⚠️ 应用初始化不完整,部分功能可能受限` ) const status = appInit.getInitStatus () logger.warn (`${LOG_TAG.ENTRY_ABILITY} 详细状态: ${JSON .stringify(status)} ` ) logger.warn (`${LOG_TAG.ENTRY_ABILITY} ` ) } logger.info (`${LOG_TAG.ENTRY_ABILITY} ========================================` ) }
printInitStatus()打印的是每个小模块的细则,而isFullyInitialized()则是检查是否所有模块都初始化成功,打印的是整体的初始化情况,两者并不一致。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 Ability onCreate EntryAbility: 应用启动,开始初始化流程 AppInit: ========== 开始阶段 1:基础模块初始化 ========== AppInit: 步骤 1/4:初始化数据库模块... KVDatabase: Succeeded in creating KVManager. KVDatabase: 数据库管理对象创建成功。 AppInit: ✓ KV 数据库初始化成功 AppInit: ✓ 偏好设置数据库初始化成功 AppInit: 步骤 2/4:加载用户配置... PreferenceDB: Has ColorMode data: false PreferenceDB: Has FontSize data: false PreferenceDB: Has FontSize data: false UserConfigManager: 无用户配置持久化数据,执行默认配置设置 PreferenceDB: Has ColorMode data: false UserConfigManager: preferenceDB.hasData(PreferenceEnum.COLOR_MODE)=false PreferenceDB: push data: key=ColorMode,value=2 PreferenceDB: Has FontSize data: false UserConfigManager: preferenceDB.hasData(PreferenceEnum.FONT_SIZE)=false PreferenceDB: push data: key=FontSize,value=16 PreferenceDB: Get data ColorMode: 2 PreferenceDB: Get data FontSize: 16 UserConfigManager: 用户首选项持久化数据读取成功,colorMode=2,fontSize=16 AppInit: ✓ 用户配置加载成功 AppInit: 步骤 3/4:初始化业务管理器... KVDatabase: Succeeded in creating KVManager. KVDatabase: 数据库管理对象创建成功。 Ability onWindowStageCreate EntryAbility: 窗口创建,等待阶段 1 完成... Ability onForeground EntryAbility: 应用进入前台 PreferenceDB: The key FontSize changed PreferenceDB: The key ColorMode changed KVDatabase: 成功获取storeId:HongYiXunKVDB数据库实例对象 NewsManager: init: 获取appKVDb成功 AppInit: ✓ 新闻管理器初始化成功 AppInit: 步骤 4/4:预加载应用数据... AxiosHttp: 进入AxiosHttp.request URL = /api/health AxiosHttp: 进入AxiosHttp.request URL = /api/banner/status AppInit: ========== 阶段 1 完成:基础模块初始化成功 ========== EntryAbility: ✓ 阶段 1 初始化成功 EntryAbility: 开始阶段 2 初始化... AppInit: ========== 开始阶段 2:窗口相关初始化 ========== AppInit: 初始化颜色模式管理器... ColorModManager: applicationContext初始化成功 ColorModManager: initColoModSetting 2: AppStorageV2colorModel = 2 AppInit: ✓ 颜色模式管理器初始化成功 AppInit: ========== 阶段 2 完成:窗口相关初始化成功 ========== EntryAbility: ✓ 阶段 2 初始化成功 Succeeded in loading the content. EntryAbility: 启动页加载成功 EntryAbility: 开始阶段 3 初始化... AppInit: ========== 开始阶段 3:UI 依赖模块初始化 ========== AppInit: 初始化 Markdown 配置... AppInit: ✓ Markdown 配置成功,字体大小: 16 AppInit: ✓ Markdown 配置初始化成功 AppInit: ========== 阶段 3 完成:UI 依赖模块初始化成功 ========== EntryAbility: ✓ 阶段 3 初始化成功 EntryAbility: 窗口宽度已存储到 AppStorageV2: 1320px
在经过如此处理之后,输出结果的稳定性得到了大幅提升,经过20次的启动测试均未再出现异步函数执行顺序导致的初始化状态错误。
异步任务管理的关键函数 在我们AppInit的异步函数控制中使用了大量的Promise类内置的静态方法,同时也使用了async/await的处理方式,接下来我们来着重解析一下这些方法的作用。
async/await与Promise首先我们要明确async/await与Promise的关系,async/await是Promise的语法糖,它可以让我们在异步函数中使用同步的代码风格,而不需要使用回调函数或者then方法。
这里我们可以从函数的返回值类型来看。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 private async initManagers (context : common.UIAbilityContext ): Promise <boolean > { try { const newsManagerInitSuccess = await newsManager.init (context) if (newsManagerInitSuccess) { logger.info (`${LOG_TAG.APP_INIT} ✓ 新闻管理器初始化成功` ) this .initStatus .managers = true return true } else { logger.error (`${LOG_TAG.APP_INIT} ✗ 新闻管理器初始化失败 - 原因:无法获取 KV 数据库实例` ) return false } } catch (error) { logger.error (`${LOG_TAG.APP_INIT} ✗ 管理器初始化异常 - 原因:${JSON .stringify(error)} ` ) return false } }
这个函数中只包含了一个异步的耗时操作,同时我们的boolean类型的返回值表示的含义是初始化管理器是否成功,是强依赖于新闻管理器的初始化结果的,所以我们需要等待新闻管理器的初始化完成之后才能返回结果。对于这种单一的异步操作函数我们直接使用async/await的方式来处理,和使用then方法的方式没有区别,同时可以使代码风格更加简洁。
我们如果直接调用initManagers这个函数,获取到的是一个Promise对象,而并不是boolean类型的结果。只有等待其操作完成后,通过await或者.then()才能获取到真正的boolean值。
这里需要注意的是,当一个函数被标记为async时,它会自动返回一个Promise对象。这意味着调用者必须使用异步方式(await或.then())来处理结果。这种设计虽然简化了异步代码的编写,但也意味着任何调用async函数的代码也都变成了异步的,形成了异步调用的链条效应。在复杂的初始化流程中,这种异步传播需要谨慎管理,以避免出现执行顺序不确定的问题。
接下来我们来更进一步的解析一下所谓的异步调用链效应。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 private async initManagers (context : common.UIAbilityContext ): Promise <boolean > { try { const newsManagerInitSuccess = await newsManager.init (context) if (newsManagerInitSuccess) { logger.info (`${LOG_TAG.APP_INIT} ✓ 新闻管理器初始化成功` ) this .initStatus .managers = true return true } else { logger.error (`${LOG_TAG.APP_INIT} ✗ 新闻管理器初始化失败 - 原因:无法获取 KV 数据库实例` ) return false } } catch (error) { logger.error (`${LOG_TAG.APP_INIT} ✗ 管理器初始化异常 - 原因:${JSON .stringify(error)} ` ) return false } } async init (context : common.UIAbilityContext ): Promise <boolean > { kvDatabase.init (context) const res = await kvDatabase.getKVStoreById (APP_KV_DB_ID ) if (res) { this .appKVDb = res logger.info (`${LOG_TAG.NEWS_MANAGER} init: 获取appKVDb成功` ) return true } logger.error (`${LOG_TAG.NEWS_MANAGER} 初始化失败` ) return false } async getKVStoreById (storeId :string ):Promise <distributedKVStore.SingleKVStore |null >{ if (this .kvManager ) { try { const options :distributedKVStore.Options = { createIfMissing : true , securityLevel : distributedKVStore.SecurityLevel .S1 , kvStoreType :distributedKVStore.KVStoreType .SINGLE_VERSION } const kVStore :distributedKVStore.SingleKVStore = await this .kvManager .getKVStore (storeId,options) if (kVStore) { logger.info (`${LOG_TAG.KV_DATABASE} 成功获取storeId:${storeId} 数据库实例对象` ) this .kvManager .on ('distributedDataServiceDie' ,()=> { logger.warn (`${LOG_TAG.KV_DATABASE} 数据库服务订阅发生变更` ) }) return kVStore } }catch (e){ let err = e as BusinessError logger.error (`${LOG_TAG.KV_DATABASE} 获取KV数据库实例对象异常,异常信息: ${err.message} ` ) } } return null } getKVStore<T>(storeId : string , options : Options ): Promise <T>;
我将整个调用链条所涉及到的全部函数都列出来了,其实可以看出整个异步调用链条的根源是来自getKVStore函数,这是我们作为应用开发者所能接触到的最底层的一个系统接口,更深层的实现就与开发者无关了,就如同计算机网络中下层协议对上层透明一样。为了方便应用的数据管理我们封装了KVDatabase类、NewsManager类、AppInit类。
层层封装的结构分析 让我们先梳理一下整个调用链条的层级关系:
1 2 3 4 5 6 7 8 9 第1层(系统接口): kvManager.getKVStore() -> Promise<SingleKVStore> ↓ 第2层(数据库封装): kvDatabase.getKVStoreById() -> Promise<SingleKVStore | null> ↓ 第3层(业务管理器): newsManager.init() -> Promise<boolean> ↓ 第4层(初始化管理器): appInit.initManagers() -> Promise<boolean> ↓ 第5层(阶段初始化): appInit.initPhase1_BaseModules() -> Promise<boolean>
每一层封装都在原有功能的基础上添加了新的职责:
第2层 KVDatabase :添加了错误处理、日志记录、实例管理
第3层 NewsManager :添加了业务逻辑封装、数据库实例缓存
第4层 initManagers :添加了状态追踪、多管理器协调
第5层 initPhase1 :添加了阶段划分、步骤编排、进度报告
层层封装对应用架构的影响 正面影响 1. 职责分离与单一职责原则
每一层封装都有其明确的职责边界,这种设计符合SOLID原则中的单一职责原则:
KVDatabase类:负责键值数据库的底层操作,屏蔽系统接口的复杂性
NewsManager类:负责新闻数据的业务逻辑,不关心数据库的具体实现
AppInit类:负责应用的初始化流程编排,不关心各模块的内部实现细节
这种分层使得每个模块的代码更加内聚,修改某一层的实现不会影响其他层。比如我们后续如果要将键值数据库换成关系型数据库,只需要修改KVDatabase类的实现,而NewsManager和AppInit的代码无需改动。
2. 代码复用性提升
通过封装,我们避免了代码重复。比如kvDatabase.getKVStoreById()这个方法在项目中被多个Manager调用:
1 2 3 4 5 6 7 8 const res = await kvDatabase.getKVStoreById (APP_KV_DB_ID )const userStore = await kvDatabase.getKVStoreById (USER_KV_DB_ID )const configStore = await kvDatabase.getKVStoreById (CONFIG_KV_DB_ID )
如果没有这层封装,每个Manager都需要重复编写获取数据库的逻辑、错误处理、日志记录等代码,这会导致大量的代码重复和维护困难。
3. 错误处理的层次化
每一层都可以根据自己的职责添加适当的错误处理策略:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 async getKVStoreById (storeId :string ):Promise <distributedKVStore.SingleKVStore |null >{ try { const kVStore = await this .kvManager .getKVStore (storeId,options) return kVStore } catch (e) { logger.error (`获取KV数据库实例对象异常` ) return null } } async init (context : common.UIAbilityContext ): Promise <boolean > { const res = await kvDatabase.getKVStoreById (APP_KV_DB_ID ) if (res) { this .appKVDb = res return true } return false } private async initManagers (context : common.UIAbilityContext ): Promise <boolean > { const newsManagerInitSuccess = await newsManager.init (context) if (newsManagerInitSuccess) { this .initStatus .managers = true } else { logger.error (`新闻管理器初始化失败` ) } return newsManagerInitSuccess }
这种层次化的错误处理使得异常可以在最合适的层级被处理,上层代码不需要关心底层的具体异常类型,只需要关心操作是否成功。
负面影响 1. 性能开销
每一层的封装都会带来一定的性能开销,主要体现在:
函数调用栈的增加 :从getKVStore到最终的initPhase1,需要经过5层函数调用
Promise链条的延长 :每一层都是一个Promise,意味着至少5次的Promise状态转换
错误处理的重复 :每一层都可能有try-catch,增加了错误检查的次数
不过在应用初始化这种非高频场景中,这些性能开销是可以接受的。如果是在高频调用的场景(比如滚动列表的渲染),就需要仔细权衡封装层次。
2. 调试复杂度增加
当出现问题时,需要逐层排查才能定位问题根源。比如当新闻管理器初始化失败时,可能的原因有:
系统层:kvManager.getKVStore()调用失败
封装层:KVDatabase初始化失败,kvManager为null
业务层:storeId配置错误
调用层:context传递错误
需要通过日志输出才能快速定位问题所在的层级,这就是为什么我们在每一层都添加了详细的日志记录。
3. 异步链条的传播效应
这是最重要也是最容易被忽视的影响。一旦底层函数是异步的,整个调用链条都会变成异步:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 async getKVStore () -> Promise <T>async getKVStoreById () -> Promise <SingleKVStore |null >async init () -> Promise <boolean >async initManagers () -> Promise <boolean >async initPhase1_BaseModules () -> Promise <boolean >onCreate ( ) { this .phase1Promise = appInit.initPhase1_BaseModules (this .context ) }
这种”异步传染”是不可避免的,一旦某个底层函数返回Promise,所有依赖它的上层函数都必须处理这个异步性。
层层封装对异步管理的影响 1. 异步操作的串行化 由于每一层都依赖于下一层的执行结果,这些异步操作必然是串行执行的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 async initPhase1_BaseModules ( ) { const dbInitSuccess = await this .initDatabases (uiAbilityContext) if (!dbInitSuccess) return false const configInitSuccess = this .initUserConfig (uiAbilityContext) const managersInitSuccess = await this .initManagers (uiAbilityContext) await this .preloadData () }
虽然我们使用了await来等待异步操作完成,但这种串行化也意味着总耗时是所有步骤耗时的总和。如果某个步骤耗时较长,会直接影响整体的初始化速度。
2. 异步操作的并行优化 在层层封装的架构下,我们仍然可以在合适的层级引入并行优化。比如在preloadData()中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 private async preloadData (): Promise <void > { try { Promise .all ([ newsManager.updateNewsListToDB (), newsManager.updateNewsSwiperToDB () ]).then (() => { logger.info (`数据预加载完成` ) }).catch ((error : Error ) => { logger.warn (`数据预加载失败: ${JSON .stringify(error)} ` ) }) } catch (error) { logger.warn (`数据预加载异常: ${JSON .stringify(error)} ` ) } }
这里我们使用Promise.all()让新闻列表和轮播图的加载并行进行,而不是串行等待。这种优化可以在不破坏封装结构的前提下提升性能。
这里我们额外添加一些针对于Promise.all()的原理解析:
Promise.all()的工作机制
Promise.all()是JavaScript/TypeScript中用于处理多个异步操作的静态方法,它的核心特点是:
并行启动 :接收一个Promise数组,会立即启动所有Promise,而不是等待前一个完成
全部等待 :等待数组中所有Promise都resolve后才返回结果
快速失败 :只要有一个Promise reject,整个Promise.all()就会立即reject
让我们通过代码对比来理解串行与并行的区别:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 async function serialLoad ( ) { const startTime = Date .now () const newsList = await newsManager.updateNewsListToDB () console .log (`新闻列表加载完成: ${Date .now() - startTime} ms` ) const swiper = await newsManager.updateNewsSwiperToDB () console .log (`轮播图加载完成: ${Date .now() - startTime} ms` ) console .log (`串行总耗时: ${Date .now() - startTime} ms` ) } async function parallelLoad ( ) { const startTime = Date .now () const results = await Promise .all ([ newsManager.updateNewsListToDB (), newsManager.updateNewsSwiperToDB () ]) console .log (`并行总耗时: ${Date .now() - startTime} ms` ) }
在我们的实际场景中,如果新闻列表加载需要800ms,轮播图加载需要600ms:
串行执行 :总耗时 = 800ms + 600ms = 1400ms
并行执行 :总耗时 = max(800ms, 600ms) = 800ms
性能提升 :约43%的启动速度提升
Promise.all()的内部执行流程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 function promiseAll (promises : Promise <any >[] ): Promise <any []> { return new Promise ((resolve, reject ) => { const results : any [] = [] let completedCount = 0 promises.forEach ((promise, index ) => { promise .then (value => { results[index] = value completedCount++ if (completedCount === promises.length ) { resolve (results) } }) .catch (error => { reject (error) }) }) }) }
从这个实现可以看出几个关键点:
立即执行 :forEach会立即遍历所有Promise,触发它们的执行,而不是等待前一个完成
结果顺序 :通过results[index]保证返回结果的顺序与输入顺序一致,即使某个Promise先完成
计数机制 :通过completedCount追踪已完成的Promise数量
快速失败 :任何一个Promise的reject都会导致整体reject,不会等待其他Promise
在我们项目中的实际应用
回到我们的preloadData()方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 private async preloadData (): Promise <void > { try { Promise .all ([ newsManager.updateNewsListToDB (), newsManager.updateNewsSwiperToDB () ]).then (() => { logger.info (`数据预加载完成` ) }).catch ((error : Error ) => { logger.warn (`数据预加载失败: ${JSON .stringify(error)} ` ) }) } catch (error) { logger.warn (`数据预加载异常: ${JSON .stringify(error)} ` ) } }
这里有一个值得注意的设计细节:我们没有使用await 来等待Promise.all():
1 2 3 4 5 Promise .all ([...]).then (...) await Promise .all ([...])
这样做的原因是:
数据预加载属于非关键路径 ,失败不应该阻止应用启动
用户可以先看到界面,数据稍后加载完成后再显示
如果网络较慢,不会让用户等待过长时间才看到界面
Promise.all()的风险与替代方案
虽然Promise.all()很强大,但也有其局限性:
风险1:一个失败导致全部失败
1 2 3 4 5 6 7 Promise .all ([ newsManager.updateNewsListToDB (), newsManager.updateNewsSwiperToDB () ]).catch (() => { })
解决方案:使用Promise.allSettled()
1 2 3 4 5 6 7 8 9 10 11 12 13 const results = await Promise .allSettled ([ newsManager.updateNewsListToDB (), newsManager.updateNewsSwiperToDB () ]) results.forEach ((result, index ) => { if (result.status === 'fulfilled' ) { logger.info (`任务${index} 成功: ${result.value} ` ) } else { logger.warn (`任务${index} 失败: ${result.reason} ` ) } })
这种方式更加健壮,即使某个数据源失败,其他数据仍然可以正常显示。
风险2:并发请求过多导致资源竞争
1 2 3 4 5 6 const promises = []for (let i = 0 ; i < 100 ; i++) { promises.push (fetchData (i)) } await Promise .all (promises)
解决方案:分批执行
1 2 3 4 5 6 7 8 9 10 11 12 13 async function batchLoad (tasks : Function [], concurrency : number = 5 ) { const results : any [] = [] for (let i = 0 ; i < tasks.length ; i += concurrency) { const batch = tasks.slice (i, i + concurrency) const batchResults = await Promise .all (batch.map (task => task ())) results.push (...batchResults) logger.info (`完成批次 ${i / concurrency + 1 } ,已加载 ${results.length} /${tasks.length} ` ) } return results }
性能监控与调优
在实际开发中,我们可以添加性能监控来验证并行优化的效果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 private async preloadData (): Promise <void > { const startTime = Date .now () try { const promises = [ this .measureTime ('新闻列表' , newsManager.updateNewsListToDB ()), this .measureTime ('轮播图' , newsManager.updateNewsSwiperToDB ()) ] await Promise .all (promises) const totalTime = Date .now () - startTime logger.info (`${LOG_TAG.APP_INIT} 数据预加载完成,总耗时: ${totalTime} ms` ) } catch (error) { logger.warn (`${LOG_TAG.APP_INIT} 数据预加载失败: ${JSON .stringify(error)} ` ) } } private async measureTime<T>(taskName : string , promise : Promise <T>): Promise <T> { const start = Date .now () try { const result = await promise logger.info (`${LOG_TAG.APP_INIT} ${taskName} 完成,耗时: ${Date .now() - start} ms` ) return result } catch (error) { logger.error (`${LOG_TAG.APP_INIT} ${taskName} 失败,耗时: ${Date .now() - start} ms` ) throw error } }
通过这样的监控,我们可以在开发阶段就发现性能瓶颈,并针对性地进行优化。
小结
Promise.all()是异步编程中非常重要的工具,它让我们能够在保持代码清晰度的同时显著提升性能。关键要点:
适用场景 :多个独立的异步操作,彼此之间没有依赖关系
性能收益 :总耗时从所有任务之和降低到最慢任务的耗时
错误处理 :需要考虑部分失败的情况,必要时使用Promise.allSettled()
并发控制 :大量并发请求时要考虑分批执行,避免资源耗尽
监控调优 :添加性能监控,用数据驱动优化决策
关键点在于识别哪些操作是可以并行的:
数据库初始化和用户配置加载 :不能并行,因为配置加载依赖数据库
新闻列表和轮播图加载 :可以并行,它们之间没有依赖关系
这也是我之前所提到的拓扑学,我们需要理清楚各个模块之间的依赖关系,才能设计出合理的并行策略。
3. 异步状态的管理复杂度 在多层异步调用中,状态管理变得更加复杂。我们需要追踪每一层的执行状态:
1 2 3 4 5 6 7 private initStatus : InitStatus = { databases : false , userConfig : false , managers : false , appStorageV2 : false , markdown : false }
这个状态对象需要在合适的时机更新,但由于异步操作的存在,更新时机很容易出错:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 async initManagers ( ) { newsManager.init (context) this .initStatus .managers = true return true } async initManagers ( ) { const success = await newsManager.init (context) if (success) { this .initStatus .managers = true } return success }
4. 异步链条中的错误传播 在层层封装的异步调用中,错误的传播路径需要精心设计:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 async getKVStore ( ) { throw new Error ("Database connection failed" ) } async getKVStoreById ( ) { try { return await this .kvManager .getKVStore (storeId, options) } catch (e) { logger.error (`获取KV数据库异常` ) return null } } async init ( ) { const res = await kvDatabase.getKVStoreById (APP_KV_DB_ID ) if (res) { return true } return false } async initPhase1 ( ) { const dbInitSuccess = await this .initDatabases (context) if (!dbInitSuccess) { logger.error (`数据库初始化失败,终止初始化流程` ) return false } }
这种设计模式将异常转换为返回值,使得错误处理更加可控,避免了未捕获异常导致的应用崩溃。但代价是需要在每一层都进行状态检查。
实践经验总结 通过这次AppInit的重构和异步管理的实践,我总结出以下几点经验:
1. 封装层次要适度
不是封装层次越多越好,也不是越少越好。关键是每一层都要有其存在的价值:
如果某一层只是简单的转发调用,没有添加任何额外逻辑,那这一层可能是多余的
如果某一层承担了过多的职责,那可能需要进一步拆分
2. 异步操作要明确标注
在ts和ArkTS中,一定要明确标注函数的返回类型:
1 2 3 4 5 async init (context : common.UIAbilityContext ): Promise <boolean >async init (context : common.UIAbilityContext )
明确的类型标注可以帮助IDE提供更好的代码补全,也能让其他开发者一眼看出这是一个异步函数。
3. 日志记录要分层详细
每一层都应该有自己的日志记录,且要包含足够的上下文信息:
1 2 3 logger.info (`${LOG_TAG.APP_INIT} 步骤 1/4: 初始化数据库模块...` ) logger.info (`${LOG_TAG.KV_DATABASE} 成功获取storeId:${storeId} 数据库实例对象` ) logger.info (`${LOG_TAG.NEWS_MANAGER} init: 获取appKVDb成功` )
通过不同的LOG_TAG和详细的描述,可以快速定位问题所在的层级。
4. 状态管理要及时准确
在异步操作完成后立即更新状态,不要延迟,这也包含了数据库中所学的原子化操作的思想,我们虽然不可能在异步操作执行成功的“时刻”进行分秒不差的同步状态更新,但我们可以将操作完成到状态更新之间的操作尽可能的缩小,压缩到所有操作产生的延时都可以小到忽略不计,将任务对象与其状态标识符进行“强绑定”:
1 2 3 4 5 const newsManagerInitSuccess = await newsManager.init (context)if (newsManagerInitSuccess) { this .initStatus .managers = true logger.info (`新闻管理器初始化成功` ) }
5. 要为异步操作预留缓冲时间
如同我们在printFinalInitStatus()中使用setTimeout一样,要考虑到异步操作的不确定性:
1 2 3 setTimeout (() => { this .printFinalInitStatus () }, 100 )
这种设计虽然看起来不够优雅,但在复杂的异步场景中是必要的容错机制。
对于AI辅助开发的思考 在这次重构中,Claude提供的代码质量确实很高,但也暴露了一些AI的局限性:
AI对异步执行顺序的理解有限 :最初的版本没有考虑到异步操作可能晚于状态打印执行的问题,需要人工发现并修复
AI倾向于过度工程化 :生成的代码注释非常详细,封装层次也很完整,但可能对小型项目来说过于复杂
AI缺乏实际运行环境的感知 :只有在真实设备上运行才能发现日志顺序的问题
因此,AI辅助开发的最佳实践应该是:AI负责生成规范化的代码框架,人类负责根据实际运行情况进行调优 。就像这次重构,Claude提供了优秀的架构设计和详细的注释,而我通过实际测试发现并修复了异步执行顺序的问题,两者结合才能产出高质量的代码。