UNPKG

2.94 kBJavaScriptView Raw
1"use strict";
2var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4 return new (P || (P = Promise))(function (resolve, reject) {
5 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8 step((generator = generator.apply(thisArg, _arguments || [])).next());
9 });
10};
11Object.defineProperty(exports, "__esModule", { value: true });
12const debug_1 = require("debug");
13const Time_1 = require("./Time");
14let Debug = debug_1.debug('server-libs');
15/*提供一个加载流程,如果某一个步骤失败的话,会等待一定时间后重新调用,知道成功为止*/
16class InitMoudle {
17 static regist(caller, func, ...args) {
18 this.initLoad.push({
19 func: func,
20 args: args,
21 caller: caller
22 });
23 }
24 static wait(num) {
25 return new Promise(function (resolve) {
26 setTimeout(() => {
27 resolve();
28 }, num);
29 });
30 }
31 static startApp() {
32 return __awaiter(this, void 0, void 0, function* () {
33 while (true) {
34 try {
35 yield this.doWork();
36 break;
37 }
38 catch (e) {
39 let unit = this.initLoad[this.initStep];
40 console.log(`init failed at step ${this.initStep} <${unit.caller.name}> wait ${this.initWait / 1000}s to reinit`);
41 e && Debug('error', e);
42 }
43 finally {
44 yield this.wait(this.initWait);
45 }
46 }
47 return true;
48 });
49 }
50 static doWork() {
51 return __awaiter(this, void 0, void 0, function* () {
52 for (let i = 0; i < this.initLoad.length; i++) {
53 let unit = this.initLoad[i];
54 if (this.checkStep(i)) {
55 yield unit.func.apply(unit.caller, unit.args);
56 console.log(`${unit.caller.name} init ok at Time`, Time_1.LocalDate.formateString());
57 this.setStep(i + 1);
58 }
59 }
60 return true;
61 });
62 }
63 static checkStep(num) {
64 if (num == this.initStep)
65 return true;
66 return false;
67 }
68 static setStep(num) {
69 this.initStep = Math.max(this.initStep, num);
70 return true;
71 }
72}
73exports.InitMoudle = InitMoudle;
74InitMoudle.initLoad = [];
75InitMoudle.initStep = 0;
76InitMoudle.initWait = 3000;