UNPKG

600 BJavaScriptView Raw
1class LazyPromise {
2 constructor(func, params) {
3 this._func = func;
4 this._params = params;
5 this._promise = undefined; // not call `func(...params)` immediately
6 }
7
8 async then(resolve, reject) {
9 this._promise = this._promise || this._func(...this._params);
10
11 try {
12 return resolve(await this._promise);
13 } catch (e) {
14 return reject(e);
15 }
16 }
17
18 async catch(callback) {
19 return this.then(v => v, callback);
20 }
21
22 async finally(callback) {
23 try {
24 return await this;
25 } finally {
26 await callback();
27 }
28 }
29}
30
31module.exports = LazyPromise;