Skip to content

Commit fb67c87

Browse files
authored
Optimise promise finally
PR-URL: #4
1 parent 9d7f3b8 commit fb67c87

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

JavaScript/6-promise.js

+11-13
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ class Queue {
55
this.concurrency = concurrency;
66
this.count = 0;
77
this.waiting = [];
8-
this.promises = [];
98
this.onProcess = null;
109
this.onDone = null;
1110
this.onSuccess = null;
@@ -31,25 +30,24 @@ class Queue {
3130
const task = this.waiting.shift();
3231
this.onProcess(task)
3332
.then(
34-
(res) => {
35-
if (this.onSuccess) this.onSuccess(res);
36-
if (this.onDone) this.onDone(null, res);
37-
},
38-
(err) => {
39-
if (this.onFailure) this.onFailure(err);
40-
if (this.onDone) this.onDone(err);
41-
}
33+
(res) => void this.finish(null, res),
34+
(err) => void this.finish(err)
4235
)
4336
.finally(() => {
4437
this.count--;
45-
if (this.count === 0 && this.waiting.length === 0) {
46-
if (this.onDrain) this.onDrain();
47-
}
48-
this.next();
38+
if (this.waiting.length > 0) this.next();
4939
});
5040
}
5141
}
5242

43+
finish(err, res) {
44+
const { onFailure, onSuccess, onDone, onDrain } = this;
45+
if (err && onFailure) onFailure(err, res);
46+
else if (onSuccess) onSuccess(res);
47+
if (onDone) onDone(err, res);
48+
if (this.count === 0 && this.waiting.length === 0 && onDrain) onDrain();
49+
}
50+
5351
process(listener) {
5452
this.onProcess = listener;
5553
return this;

0 commit comments

Comments
 (0)