-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path3-advanced.js
More file actions
61 lines (53 loc) · 1.36 KB
/
3-advanced.js
File metadata and controls
61 lines (53 loc) · 1.36 KB
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
'use strict';
class PaymentService {
constructor(type, active) {
this.type = type;
this.active = active;
}
processPayment({ to, amount, check }, callback) {
if (check) {
if (typeof amount !== 'number') {
const error = new Error('Amount expected to be number');
return void callback(error);
}
if (amount <= 0) {
const error = new Error('Amount should be greater than 0');
return void callback(error);
}
}
console.log(`Payment: ${amount} to ${to} by ${this.type}`);
return void callback(null);
}
}
class Bank extends PaymentService {
constructor(type = 'card', active = true) {
super(type, active);
}
processPayment({ to, amount, check = true }, callback) {
if (this.active) {
super.processPayment({ to, amount, check }, callback);
} else {
callback(new Error('Service is not active'));
}
}
async pay(options) {
const { promise, resolve, reject } = Promise.withResolvers();
super.processPayment(options, (error) => {
if (error) reject(error);
else resolve();
});
return promise;
}
}
// Usage
const main = async () => {
const bank = new Bank('wire');
console.log(bank);
try {
await bank.pay({ to: 'contractor', amount: 1000 });
console.log('Success!');
} catch (error) {
console.error(error);
}
};
main();