@lppx/nlearn 1.1.7 → 1.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/src/cli/cli.js +12 -6
  2. package/dist/src/demo/class/01-/345/237/272/347/241/200/346/246/202/345/277/265.js +6 -0
  3. package/dist/src/demo/class/02-/347/273/247/346/211/277/344/270/216/345/244/232/346/200/201.js +6 -0
  4. package/dist/src/demo/class/03-/351/235/231/346/200/201/346/210/220/345/221/230/344/270/216/345/215/225/344/276/213.js +6 -0
  5. package/dist/src/demo/class/04-/346/216/245/345/217/243/344/270/216/345/256/236/347/216/260.js +7 -0
  6. package/dist/src/demo/commander/01-/345/237/272/347/241/200/346/246/202/345/277/265.js +6 -0
  7. package/dist/src/demo/commander/02-/345/221/275/344/273/244/347/263/273/347/273/237.js +6 -0
  8. package/dist/src/demo/commander/03-/351/253/230/347/272/247/347/211/271/346/200/247.js +6 -0
  9. package/dist/src/demo/commander/04-/345/256/236/346/210/230/346/241/210/344/276/213.js +4 -0
  10. package/dist/src/demo/esm/01-/345/237/272/347/241/200/346/246/202/345/277/265.js +6 -0
  11. package/dist/src/demo/esm/02-/345/257/274/345/207/272/350/257/255/346/263/225.js +8 -0
  12. package/dist/src/demo/esm/03-/345/257/274/345/205/245/350/257/255/346/263/225.js +9 -2
  13. package/dist/src/demo/esm/04-/345/256/236/346/210/230/346/241/210/344/276/213.js +8 -0
  14. package/dist/src/demo/fuse/01-/345/237/272/347/241/200/346/246/202/345/277/265.js +5 -0
  15. package/dist/src/demo/fuse/02-/351/253/230/347/272/247/346/220/234/347/264/242.js +6 -0
  16. package/dist/src/demo/fuse/03-/351/205/215/347/275/256/350/257/246/350/247/243.js +6 -0
  17. package/dist/src/demo/fuse/04-/345/256/236/346/210/230/346/241/210/344/276/213.js +5 -0
  18. package/dist/src/demo/inquirer/01-/345/237/272/347/241/200/346/246/202/345/277/265.js +6 -0
  19. package/dist/src/demo/inquirer/02-/351/200/211/346/213/251/347/261/273/345/236/213.js +6 -0
  20. package/dist/src/demo/inquirer/03-/351/253/230/347/272/247/347/211/271/346/200/247.js +6 -0
  21. package/dist/src/demo/inquirer/04-/345/256/236/346/210/230/346/241/210/344/276/213.js +5 -0
  22. package/dist/src/demo/promise-async/01-/345/237/272/347/241/200/346/246/202/345/277/265.js +267 -0
  23. package/dist/src/demo/promise-async/02-/345/271/266/345/217/221/346/216/247/345/210/266.js +304 -0
  24. package/dist/src/demo/promise-async/03-/351/253/230/347/272/247/346/250/241/345/274/217.js +311 -0
  25. package/dist/src/demo/promise-async/04-/345/256/236/346/210/230/346/241/210/344/276/213.js +349 -0
  26. package/dist/src/demo/prompts/01-/345/237/272/347/241/200/346/246/202/345/277/265.js +5 -0
  27. package/dist/src/demo/prompts/02-/346/217/220/347/244/272/347/261/273/345/236/213.js +7 -0
  28. package/dist/src/demo/prompts/03-/351/253/230/347/272/247/347/211/271/346/200/247.js +6 -0
  29. package/dist/src/demo/prompts/04-/345/256/236/346/210/230/346/241/210/344/276/213.js +4 -0
  30. package/dist/src/demo/prompts/05-/346/250/241/347/263/212/350/241/245/345/205/250.js +6 -0
  31. package/dist/src/demo/yargs/01-/345/237/272/347/241/200/346/246/202/345/277/265.js +5 -0
  32. package/dist/src/demo/yargs/02-/345/221/275/344/273/244/347/263/273/347/273/237.js +6 -0
  33. package/dist/src/demo/yargs/03-/351/253/230/347/272/247/347/211/271/346/200/247.js +6 -0
  34. package/dist/src/demo/yargs/04-/345/256/236/346/210/230/346/241/210/344/276/213.js +5 -0
  35. package/package.json +1 -1
@@ -43,11 +43,14 @@ const promises_1 = require("node:fs/promises");
43
43
  const node_path_1 = require("node:path");
44
44
  const prompts_1 = __importDefault(require("prompts"));
45
45
  const fuse_js_1 = __importDefault(require("fuse.js"));
46
+ const node_console_1 = require("node:console");
46
47
  /**
47
48
  * 扫描 demo 文件夹中的所有示例函数
48
49
  */
49
50
  async function scanDemoFunctions() {
50
- const demoPath = (0, node_path_1.join)(process.cwd(), 'src', 'demo');
51
+ // cli.ts 所在目录向上找到包根目录,然后定位到 demo 目录
52
+ const demoPath = (0, node_path_1.join)(__dirname, '..', 'demo');
53
+ (0, node_console_1.log)(__dirname);
51
54
  const results = [];
52
55
  try {
53
56
  // 读取所有文件夹
@@ -58,7 +61,8 @@ async function scanDemoFunctions() {
58
61
  const folderPath = (0, node_path_1.join)(demoPath, folder.name);
59
62
  const files = await (0, promises_1.readdir)(folderPath, { withFileTypes: true });
60
63
  for (const file of files) {
61
- if (!file.isFile() || !file.name.endsWith('.ts'))
64
+ // 支持 .ts .js 文件
65
+ if (!file.isFile() || (!file.name.endsWith('.ts') && !file.name.endsWith('.js')))
62
66
  continue;
63
67
  const filePath = (0, node_path_1.join)(folderPath, file.name);
64
68
  const content = await (0, promises_1.readFile)(filePath, 'utf-8');
@@ -67,10 +71,12 @@ async function scanDemoFunctions() {
67
71
  let match;
68
72
  while ((match = functionRegex.exec(content)) !== null) {
69
73
  const functionName = match[1];
70
- const displayName = `${folder.name}@${file.name.replace('.ts', '')}@${functionName}`;
74
+ // 移除文件扩展名(支持 .ts 和 .js)
75
+ const fileNameWithoutExt = file.name.replace(/\.(ts|js)$/, '');
76
+ const displayName = `${folder.name}@${fileNameWithoutExt}@${functionName}`;
71
77
  results.push({
72
78
  folder: folder.name,
73
- file: file.name.replace('.ts', ''),
79
+ file: fileNameWithoutExt,
74
80
  functionName,
75
81
  displayName
76
82
  });
@@ -124,8 +130,8 @@ async function executeDemoFunction(demoFunc) {
124
130
  try {
125
131
  console.log(`\n正在运行: ${demoFunc.displayName}\n`);
126
132
  console.log('='.repeat(50));
127
- // 构建模块路径
128
- const modulePath = (0, node_path_1.join)(process.cwd(), 'src', 'demo', demoFunc.folder, `${demoFunc.file}.js`);
133
+ // 构建模块路径(相对于 cli.ts 所在目录)
134
+ const modulePath = (0, node_path_1.join)(__dirname, '..', 'demo', demoFunc.folder, `${demoFunc.file}.js`);
129
135
  // 动态导入模块
130
136
  const module = await Promise.resolve(`${modulePath}`).then(s => __importStar(require(s)));
131
137
  // 检查函数是否存在
@@ -5,6 +5,12 @@
5
5
  * 介绍类的基本定义、构造函数、属性和方法
6
6
  * 适用于 TypeScript 3.0+
7
7
  */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.basicClassDemo = basicClassDemo;
10
+ exports.accessModifiersDemo = accessModifiersDemo;
11
+ exports.propertyShorthandDemo = propertyShorthandDemo;
12
+ exports.getterSetterDemo = getterSetterDemo;
13
+ exports.readonlyPropertyDemo = readonlyPropertyDemo;
8
14
  // #region 示例1: 基本类定义
9
15
  class Person {
10
16
  constructor(name, age) {
@@ -5,6 +5,12 @@
5
5
  * 介绍类的继承、方法重写、super 关键字和多态性
6
6
  * 适用于 TypeScript 3.0+
7
7
  */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.basicInheritanceDemo = basicInheritanceDemo;
10
+ exports.methodOverrideDemo = methodOverrideDemo;
11
+ exports.polymorphismDemo = polymorphismDemo;
12
+ exports.abstractClassDemo = abstractClassDemo;
13
+ exports.protectedMemberDemo = protectedMemberDemo;
8
14
  // #region 示例1: 基本继承
9
15
  class Animal {
10
16
  constructor(name) {
@@ -5,6 +5,12 @@
5
5
  * 介绍静态属性、静态方法和单例模式的实现
6
6
  * 适用于 TypeScript 3.0+
7
7
  */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.staticMembersDemo = staticMembersDemo;
10
+ exports.staticCounterDemo = staticCounterDemo;
11
+ exports.singletonBasicDemo = singletonBasicDemo;
12
+ exports.configManagerDemo = configManagerDemo;
13
+ exports.staticFactoryDemo = staticFactoryDemo;
8
14
  // #region 示例1: 静态属性和方法
9
15
  class MathUtils {
10
16
  static add(a, b) {
@@ -5,6 +5,13 @@
5
5
  * 介绍接口定义、类实现接口、接口继承
6
6
  * 适用于 TypeScript 3.0+
7
7
  */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.singleInterfaceDemo = singleInterfaceDemo;
10
+ exports.multipleInterfacesDemo = multipleInterfacesDemo;
11
+ exports.interfaceInheritanceDemo = interfaceInheritanceDemo;
12
+ exports.methodSignatureDemo = methodSignatureDemo;
13
+ exports.sortVersions = sortVersions;
14
+ exports.genericInterfaceDemo = genericInterfaceDemo;
8
15
  class Document {
9
16
  constructor(content) {
10
17
  this.content = content;
@@ -7,6 +7,12 @@
7
7
  * 适用版本:commander ^12.0.0
8
8
  */
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.demoSimplestCLI = demoSimplestCLI;
11
+ exports.demoOptionsUsage = demoOptionsUsage;
12
+ exports.demoRequiredAndOptionalArgs = demoRequiredAndOptionalArgs;
13
+ exports.demoVariadicArgs = demoVariadicArgs;
14
+ exports.demoCustomHelp = demoCustomHelp;
15
+ exports.demoTypeConversion = demoTypeConversion;
10
16
  const commander_1 = require("commander");
11
17
  // #region 示例1: 最简单的 CLI 程序
12
18
  function demoSimplestCLI() {
@@ -6,6 +6,12 @@
6
6
  * 适用版本:commander ^12.0.0
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.demoBasicSubcommands = demoBasicSubcommands;
10
+ exports.demoCommandAliases = demoCommandAliases;
11
+ exports.demoCommandSpecificOptions = demoCommandSpecificOptions;
12
+ exports.demoNestedSubcommands = demoNestedSubcommands;
13
+ exports.demoDefaultCommand = demoDefaultCommand;
14
+ exports.demoArgumentValidation = demoArgumentValidation;
9
15
  const commander_1 = require("commander");
10
16
  // #region 示例1: 基本子命令
11
17
  function demoBasicSubcommands() {
@@ -6,6 +6,12 @@
6
6
  * 适用版本:commander ^12.0.0
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.demoAsyncCommands = demoAsyncCommands;
10
+ exports.demoErrorHandling = demoErrorHandling;
11
+ exports.demoCommandHooks = demoCommandHooks;
12
+ exports.demoConfigFileLoading = demoConfigFileLoading;
13
+ exports.demoEnvironmentVariables = demoEnvironmentVariables;
14
+ exports.demoCustomOutput = demoCustomOutput;
9
15
  const commander_1 = require("commander");
10
16
  // #region 示例1: 异步命令处理
11
17
  async function demoAsyncCommands() {
@@ -40,6 +40,10 @@ var __importStar = (this && this.__importStar) || (function () {
40
40
  };
41
41
  })();
42
42
  Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.demoFileManagerCLI = demoFileManagerCLI;
44
+ exports.demoProjectScaffolder = demoProjectScaffolder;
45
+ exports.demoTaskManagerCLI = demoTaskManagerCLI;
46
+ exports.demoDeploymentTool = demoDeploymentTool;
43
47
  const commander_1 = require("commander");
44
48
  const fs = __importStar(require("fs"));
45
49
  const path = __importStar(require("path"));
@@ -10,6 +10,12 @@
10
10
  * - CommonJS 是 Node.js 早期采用的模块系统
11
11
  * - ESM 使用 import/export,CommonJS 使用 require/module.exports
12
12
  */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.explainModuleSystem = explainModuleSystem;
15
+ exports.compareModuleSystems = compareModuleSystems;
16
+ exports.enableESMInNodejs = enableESMInNodejs;
17
+ exports.esmStrictMode = esmStrictMode;
18
+ exports.moduleScope = moduleScope;
13
19
  // #region 示例1: 什么是模块系统
14
20
  /**
15
21
  * 模块系统的作用:
@@ -5,6 +5,14 @@
5
5
  * 本文件详细介绍 ESM 的各种导出方式
6
6
  * 包括命名导出、默认导出、重导出等
7
7
  */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.demonstrateNamedExports = demonstrateNamedExports;
10
+ exports.demonstrateDefaultExport = demonstrateDefaultExport;
11
+ exports.demonstrateMixedExports = demonstrateMixedExports;
12
+ exports.demonstrateReExports = demonstrateReExports;
13
+ exports.demonstrateAggregateExports = demonstrateAggregateExports;
14
+ exports.exportCaveats = exportCaveats;
15
+ exports.runAllExportExamples = runAllExportExamples;
8
16
  // #region 示例1: 命名导出(Named Exports)
9
17
  /**
10
18
  * 命名导出:可以导出多个值,每个值都有自己的名称
@@ -6,6 +6,13 @@
6
6
  * 包括命名导入、默认导入、动态导入等
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.demonstrateNamedImports = demonstrateNamedImports;
10
+ exports.demonstrateDefaultImport = demonstrateDefaultImport;
11
+ exports.demonstrateMixedImports = demonstrateMixedImports;
12
+ exports.demonstrateDynamicImport = demonstrateDynamicImport;
13
+ exports.demonstrateSideEffectImport = demonstrateSideEffectImport;
14
+ exports.importCaveats = importCaveats;
15
+ exports.runAllExamples = runAllExamples;
9
16
  // #region 示例1: 命名导入(Named Imports)
10
17
  /**
11
18
  * 命名导入:导入模块的命名导出
@@ -145,7 +152,7 @@ async function demonstrateDynamicImport() {
145
152
  示例1: 基本用法
146
153
  ---
147
154
  // 使用 await
148
- async function loadModule() {
155
+ export async function loadModule() {
149
156
  const module = await import("./math.js");
150
157
  console.log(module.add(2, 3));
151
158
  }
@@ -158,7 +165,7 @@ import("./math.js").then(module => {
158
165
 
159
166
  示例2: 条件加载
160
167
  ---
161
- async function loadFeature(featureName) {
168
+ export async function loadFeature(featureName) {
162
169
  if (featureName === "advanced") {
163
170
  const module = await import("./advanced.js");
164
171
  return module.default;
@@ -5,6 +5,14 @@
5
5
  * 本文件通过实际案例展示 ESM 的应用场景
6
6
  * 包括模块组织、代码分割、插件系统等
7
7
  */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.demonstrateUtilsLibrary = demonstrateUtilsLibrary;
10
+ exports.demonstrateConfigSystem = demonstrateConfigSystem;
11
+ exports.demonstratePluginSystem = demonstratePluginSystem;
12
+ exports.demonstrateLazyRouting = demonstrateLazyRouting;
13
+ exports.demonstrateI18nSystem = demonstrateI18nSystem;
14
+ exports.demonstrateMicroFrontend = demonstrateMicroFrontend;
15
+ exports.runAllExamples = runAllExamples;
8
16
  // #region 示例1: 工具函数库的模块化组织
9
17
  /**
10
18
  * 案例:创建一个工具函数库,使用 ESM 进行模块化组织
@@ -12,6 +12,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.搜索字符串数组 = 搜索字符串数组;
16
+ exports.搜索对象数组 = 搜索对象数组;
17
+ exports.基础配置选项 = 基础配置选项;
18
+ exports.嵌套对象搜索 = 嵌套对象搜索;
19
+ exports.结果数量控制 = 结果数量控制;
15
20
  const fuse_js_1 = __importDefault(require("fuse.js"));
16
21
  // #region 示例1: 简单字符串数组搜索
17
22
  function 搜索字符串数组() {
@@ -11,6 +11,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
11
11
  return (mod && mod.__esModule) ? mod : { "default": mod };
12
12
  };
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.扩展搜索精确匹配 = 扩展搜索精确匹配;
15
+ exports.前缀后缀匹配 = 前缀后缀匹配;
16
+ exports.包含排除搜索 = 包含排除搜索;
17
+ exports.逻辑运算符搜索 = 逻辑运算符搜索;
18
+ exports.权重搜索 = 权重搜索;
19
+ exports.复杂查询组合 = 复杂查询组合;
14
20
  const fuse_js_1 = __importDefault(require("fuse.js"));
15
21
  // #region 示例1: 扩展搜索 - 精确匹配
16
22
  function 扩展搜索精确匹配() {
@@ -11,6 +11,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
11
11
  return (mod && mod.__esModule) ? mod : { "default": mod };
12
12
  };
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.阈值配置对比 = 阈值配置对比;
15
+ exports.位置距离配置 = 位置距离配置;
16
+ exports.最小匹配长度 = 最小匹配长度;
17
+ exports.排序配置 = 排序配置;
18
+ exports.匹配详情配置 = 匹配详情配置;
19
+ exports.完整配置示例 = 完整配置示例;
14
20
  const fuse_js_1 = __importDefault(require("fuse.js"));
15
21
  // #region 示例1: threshold 阈值配置
16
22
  function 阈值配置对比() {
@@ -11,6 +11,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
11
11
  return (mod && mod.__esModule) ? mod : { "default": mod };
12
12
  };
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.用户搜索系统 = 用户搜索系统;
15
+ exports.商品搜索与过滤 = 商品搜索与过滤;
16
+ exports.文档搜索引擎 = 文档搜索引擎;
17
+ exports.命令行工具搜索 = 命令行工具搜索;
18
+ exports.智能联系人搜索 = 智能联系人搜索;
14
19
  const fuse_js_1 = __importDefault(require("fuse.js"));
15
20
  // #region 示例1: 用户搜索系统
16
21
  function 用户搜索系统() {
@@ -10,6 +10,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
10
10
  return (mod && mod.__esModule) ? mod : { "default": mod };
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.simpleInput = simpleInput;
14
+ exports.inputWithDefault = inputWithDefault;
15
+ exports.passwordInput = passwordInput;
16
+ exports.numberInput = numberInput;
17
+ exports.confirmInput = confirmInput;
18
+ exports.multipleQuestions = multipleQuestions;
13
19
  const inquirer_1 = __importDefault(require("inquirer"));
14
20
  // #region 示例1: 简单的文本输入
15
21
  async function simpleInput() {
@@ -9,6 +9,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
9
9
  return (mod && mod.__esModule) ? mod : { "default": mod };
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.listChoice = listChoice;
13
+ exports.rawListChoice = rawListChoice;
14
+ exports.expandChoice = expandChoice;
15
+ exports.checkboxChoice = checkboxChoice;
16
+ exports.choiceWithSeparator = choiceWithSeparator;
17
+ exports.choiceWithValue = choiceWithValue;
12
18
  const inquirer_1 = __importDefault(require("inquirer"));
13
19
  // #region 示例1: 列表单选 (list)
14
20
  async function listChoice() {
@@ -9,6 +9,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
9
9
  return (mod && mod.__esModule) ? mod : { "default": mod };
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.inputValidation = inputValidation;
13
+ exports.inputFilter = inputFilter;
14
+ exports.conditionalQuestions = conditionalQuestions;
15
+ exports.dynamicDefault = dynamicDefault;
16
+ exports.dynamicChoices = dynamicChoices;
17
+ exports.loopQuestions = loopQuestions;
12
18
  const inquirer_1 = __importDefault(require("inquirer"));
13
19
  // #region 示例1: 输入验证
14
20
  async function inputValidation() {
@@ -9,6 +9,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
9
9
  return (mod && mod.__esModule) ? mod : { "default": mod };
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.projectInitWizard = projectInitWizard;
13
+ exports.databaseConfigGenerator = databaseConfigGenerator;
14
+ exports.gitCommitHelper = gitCommitHelper;
15
+ exports.envConfigManager = envConfigManager;
16
+ exports.taskManager = taskManager;
12
17
  const inquirer_1 = __importDefault(require("inquirer"));
13
18
  // #region 示例1: 项目初始化向导
14
19
  async function projectInitWizard() {
@@ -0,0 +1,267 @@
1
+ "use strict";
2
+ /**
3
+ * Promise 与 async/await 基础概念
4
+ * ================================
5
+ * 本文件介绍 Promise 的基本概念、三种状态、基本用法
6
+ * 适用于 Node.js >= 14.0.0
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.demonstratePromiseStates = demonstratePromiseStates;
10
+ exports.createAndUsePromise = createAndUsePromise;
11
+ exports.promiseChaining = promiseChaining;
12
+ exports.asyncAwaitBasics = asyncAwaitBasics;
13
+ exports.asyncAwaitErrorHandling = asyncAwaitErrorHandling;
14
+ exports.promiseStaticMethods = promiseStaticMethods;
15
+ // #region 示例1: Promise 的三种状态
16
+ /**
17
+ * Promise 有三种状态:
18
+ * - pending(进行中)
19
+ * - fulfilled(已成功)
20
+ * - rejected(已失败)
21
+ */
22
+ function demonstratePromiseStates() {
23
+ console.log('=== Promise 的三种状态 ===\n');
24
+ // 创建一个立即成功的 Promise
25
+ const fulfilledPromise = new Promise((resolve) => {
26
+ resolve('成功的结果');
27
+ });
28
+ // 创建一个立即失败的 Promise
29
+ const rejectedPromise = new Promise((_, reject) => {
30
+ reject(new Error('失败的原因'));
31
+ });
32
+ // 创建一个延迟执行的 Promise
33
+ const pendingPromise = new Promise((resolve) => {
34
+ setTimeout(() => {
35
+ resolve('延迟 1 秒后成功');
36
+ }, 1000);
37
+ });
38
+ console.log('fulfilledPromise 状态:', fulfilledPromise);
39
+ console.log('rejectedPromise 状态:', rejectedPromise);
40
+ console.log('pendingPromise 状态:', pendingPromise);
41
+ // 处理成功的 Promise
42
+ fulfilledPromise.then((result) => {
43
+ console.log('\n成功结果:', result);
44
+ });
45
+ // 处理失败的 Promise
46
+ rejectedPromise.catch((error) => {
47
+ console.log('失败原因:', error.message);
48
+ });
49
+ // 处理延迟的 Promise
50
+ pendingPromise.then((result) => {
51
+ console.log('延迟结果:', result);
52
+ });
53
+ }
54
+ // #endregion
55
+ // #region 示例2: 创建和使用 Promise
56
+ /**
57
+ * 演示如何创建和使用 Promise
58
+ */
59
+ function createAndUsePromise() {
60
+ console.log('\n=== 创建和使用 Promise ===\n');
61
+ // 模拟异步操作:读取用户数据
62
+ function fetchUserData(userId) {
63
+ return new Promise((resolve, reject) => {
64
+ console.log(`开始获取用户 ${userId} 的数据...`);
65
+ setTimeout(() => {
66
+ if (userId > 0) {
67
+ resolve({
68
+ id: userId,
69
+ name: `用户${userId}`,
70
+ });
71
+ }
72
+ else {
73
+ reject(new Error('无效的用户 ID'));
74
+ }
75
+ }, 1000);
76
+ });
77
+ }
78
+ // 使用 then/catch 处理 Promise
79
+ fetchUserData(1)
80
+ .then((user) => {
81
+ console.log('获取成功:', user);
82
+ return user.id;
83
+ })
84
+ .then((userId) => {
85
+ console.log('用户 ID:', userId);
86
+ })
87
+ .catch((error) => {
88
+ console.error('获取失败:', error.message);
89
+ })
90
+ .finally(() => {
91
+ console.log('请求结束\n');
92
+ });
93
+ // 处理失败的情况
94
+ fetchUserData(-1)
95
+ .then((user) => {
96
+ console.log('获取成功:', user);
97
+ })
98
+ .catch((error) => {
99
+ console.error('获取失败:', error.message);
100
+ });
101
+ }
102
+ // #endregion
103
+ // #region 示例3: Promise 链式调用
104
+ /**
105
+ * 演示 Promise 的链式调用
106
+ */
107
+ function promiseChaining() {
108
+ console.log('\n=== Promise 链式调用 ===\n');
109
+ // 模拟多个异步操作
110
+ function step1() {
111
+ return new Promise((resolve) => {
112
+ setTimeout(() => {
113
+ console.log('步骤 1: 获取初始值');
114
+ resolve(10);
115
+ }, 500);
116
+ });
117
+ }
118
+ function step2(value) {
119
+ return new Promise((resolve) => {
120
+ setTimeout(() => {
121
+ console.log(`步骤 2: 将 ${value} 乘以 2`);
122
+ resolve(value * 2);
123
+ }, 500);
124
+ });
125
+ }
126
+ function step3(value) {
127
+ return new Promise((resolve) => {
128
+ setTimeout(() => {
129
+ console.log(`步骤 3: 将 ${value} 加上 5`);
130
+ resolve(value + 5);
131
+ }, 500);
132
+ });
133
+ }
134
+ // 链式调用
135
+ step1()
136
+ .then((result) => step2(result))
137
+ .then((result) => step3(result))
138
+ .then((finalResult) => {
139
+ console.log('最终结果:', finalResult); // 10 * 2 + 5 = 25
140
+ })
141
+ .catch((error) => {
142
+ console.error('出错了:', error);
143
+ });
144
+ }
145
+ // #endregion
146
+ // #region 示例4: async/await 基础用法
147
+ /**
148
+ * 演示 async/await 的基础用法
149
+ * async/await 是 Promise 的语法糖,让异步代码看起来像同步代码
150
+ */
151
+ async function asyncAwaitBasics() {
152
+ console.log('\n=== async/await 基础用法 ===\n');
153
+ // 模拟异步操作
154
+ function delay(ms, value) {
155
+ return new Promise((resolve) => {
156
+ setTimeout(() => resolve(value), ms);
157
+ });
158
+ }
159
+ try {
160
+ console.log('开始执行...');
161
+ // 使用 await 等待 Promise 完成
162
+ const result1 = await delay(1000, '第一步完成');
163
+ console.log(result1);
164
+ const result2 = await delay(1000, '第二步完成');
165
+ console.log(result2);
166
+ const result3 = await delay(1000, '第三步完成');
167
+ console.log(result3);
168
+ console.log('全部完成!');
169
+ }
170
+ catch (error) {
171
+ console.error('发生错误:', error);
172
+ }
173
+ }
174
+ // #endregion
175
+ // #region 示例5: async/await 错误处理
176
+ /**
177
+ * 演示 async/await 的错误处理
178
+ */
179
+ async function asyncAwaitErrorHandling() {
180
+ console.log('\n=== async/await 错误处理 ===\n');
181
+ // 模拟可能失败的异步操作
182
+ function fetchData(shouldFail) {
183
+ return new Promise((resolve, reject) => {
184
+ setTimeout(() => {
185
+ if (shouldFail) {
186
+ reject(new Error('数据获取失败'));
187
+ }
188
+ else {
189
+ resolve('数据获取成功');
190
+ }
191
+ }, 1000);
192
+ });
193
+ }
194
+ // 方式 1: 使用 try/catch
195
+ try {
196
+ console.log('尝试获取数据...');
197
+ const data = await fetchData(false);
198
+ console.log('成功:', data);
199
+ }
200
+ catch (error) {
201
+ if (error instanceof Error) {
202
+ console.error('失败:', error.message);
203
+ }
204
+ }
205
+ // 方式 2: 使用 .catch()
206
+ console.log('\n尝试获取会失败的数据...');
207
+ const result = await fetchData(true).catch((error) => {
208
+ console.error('捕获到错误:', error.message);
209
+ return '使用默认值'; // 返回默认值
210
+ });
211
+ console.log('最终结果:', result);
212
+ }
213
+ // #endregion
214
+ // #region 示例6: Promise.resolve 和 Promise.reject
215
+ /**
216
+ * 演示 Promise.resolve 和 Promise.reject 的快捷方法
217
+ */
218
+ function promiseStaticMethods() {
219
+ console.log('\n=== Promise.resolve 和 Promise.reject ===\n');
220
+ // Promise.resolve 创建一个已成功的 Promise
221
+ const resolved = Promise.resolve('立即成功');
222
+ resolved.then((value) => {
223
+ console.log('Promise.resolve:', value);
224
+ });
225
+ // Promise.reject 创建一个已失败的 Promise
226
+ const rejected = Promise.reject(new Error('立即失败'));
227
+ rejected.catch((error) => {
228
+ console.log('Promise.reject:', error.message);
229
+ });
230
+ // Promise.resolve 可以将值包装成 Promise
231
+ async function getValue() {
232
+ const value = await Promise.resolve(42);
233
+ console.log('包装的值:', value);
234
+ }
235
+ getValue();
236
+ }
237
+ // #endregion
238
+ // 主函数:根据参数运行指定示例
239
+ if (require.main === module) {
240
+ const exampleNumber = process.argv[2];
241
+ const examples = {
242
+ '1': demonstratePromiseStates,
243
+ '2': createAndUsePromise,
244
+ '3': promiseChaining,
245
+ '4': asyncAwaitBasics,
246
+ '5': asyncAwaitErrorHandling,
247
+ '6': promiseStaticMethods,
248
+ };
249
+ if (exampleNumber && examples[exampleNumber]) {
250
+ console.log(`\n运行示例 ${exampleNumber}:\n`);
251
+ const result = examples[exampleNumber]();
252
+ if (result instanceof Promise) {
253
+ result.catch(console.error);
254
+ }
255
+ }
256
+ else {
257
+ console.log('请指定要运行的示例编号 (1-6)');
258
+ console.log('例如: ts-node src/demo/promise-async/01-基础概念.ts 1');
259
+ console.log('\n可用示例:');
260
+ console.log('1 - Promise 的三种状态');
261
+ console.log('2 - 创建和使用 Promise');
262
+ console.log('3 - Promise 链式调用');
263
+ console.log('4 - async/await 基础用法');
264
+ console.log('5 - async/await 错误处理');
265
+ console.log('6 - Promise.resolve 和 Promise.reject');
266
+ }
267
+ }