UNPKG

2.14 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const version_1 = require("./version");
4// 制作一个自己封装的promise 主要解决node8上面没有finally
5class TePromise {
6 constructor(cb) {
7 this.thenPools = [];
8 this.catchPools = [];
9 this.finallPools = [];
10 if (cb instanceof Promise) {
11 this.pm = cb;
12 }
13 else {
14 this.pm = new Promise(cb);
15 }
16 this.pm.then(this.onThen.bind(this)).catch(this.onCatch.bind(this));
17 this.pm.then = this.then.bind(this);
18 this.pm.catch = this.catch.bind(this);
19 this.pm.finally = this.finally.bind(this);
20 }
21 onThen(v) {
22 // 这里按照列表一个一个来出现异常就进入catch
23 try {
24 var fn = this.thenPools.shift();
25 while (fn) {
26 fn(v);
27 fn = this.thenPools.shift();
28 }
29 }
30 catch (e) {
31 this.onCatch(e);
32 }
33 finally {
34 this.doFinally();
35 }
36 }
37 onCatch(e) {
38 try {
39 var fn = this.catchPools.shift();
40 while (fn) {
41 fn(e);
42 fn = this.catchPools.shift();
43 }
44 }
45 catch (e) {
46 }
47 finally {
48 this.doFinally();
49 }
50 }
51 doFinally() {
52 var fn = this.finallPools.shift();
53 while (fn) {
54 fn();
55 fn = this.finallPools.shift();
56 }
57 }
58 then(onReslove, onReject) {
59 this.thenPools.push(onReslove);
60 if (onReject)
61 this.catchPools.push(onReject);
62 }
63 catch(cb) {
64 this.catchPools.push(cb);
65 }
66 finally(cb) {
67 this.finallPools.push(cb);
68 }
69}
70function createPromise(func) {
71 if (version_1.V_UnderV8) {
72 return (new TePromise(func)).pm;
73 }
74 else {
75 if (func instanceof Promise)
76 return func;
77 else
78 return new Promise(func);
79 }
80}
81exports.createPromise = createPromise;