Skip to content

Commit 6646d54

Browse files
author
yusitnikov
committed
Support Promise style instead of passing a callback
1 parent 9acc775 commit 6646d54

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

README.md

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,14 @@ The library contains only one script `fix-webm-duration.js` and has no dependenc
1111
Syntax:
1212

1313
```javascript
14-
ysFixWebmDuration(blob, duration, callback, options = {});
14+
ysFixWebmDuration(blob, duration, callback = undefined, options = {});
1515
```
1616

1717
where
1818
- `blob` is `Blob` object with file contents from `MediaRecorder`
1919
- `duration` is video duration in milliseconds (you should calculate it while recording the video)
20-
- `callback` is callback function that will receive fixed blob
20+
- `callback` is callback function that will receive fixed blob.
21+
If omitted, a `Promise` object will be returned instead.
2122
- `options` is an object of options:
2223
- `options.logger` - a callback for logging debug messages or `false`.
2324
The callback should accept one argument - the message string.
@@ -41,10 +42,17 @@ function startRecording(stream, options) {
4142
mediaRecorder.onstop = function() {
4243
var duration = Date.now() - startTime;
4344
var buggyBlob = new Blob(mediaParts, { type: 'video/webm' });
44-
45+
46+
// v1: callback-style
4547
ysFixWebmDuration(buggyBlob, duration, function(fixedBlob) {
4648
displayResult(fixedBlob);
4749
});
50+
51+
// v2: promise-style, disable logging
52+
ysFixWebmDuration(buggyBlob, duration, {logger: false})
53+
.then(function(fixedBlob) {
54+
displayResult(fixedBlob);
55+
});
4856
};
4957
mediaRecorder.ondataavailable = function(event) {
5058
var data = event.data;

fix-webm-duration.js

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,19 @@
474474
return new Blob([ this.source.buffer ], { type: 'video/webm' });
475475
};
476476

477-
return function(blob, duration, callback, options) {
477+
function fixWebmDuration(blob, duration, callback, options) {
478+
// The callback may be omitted - then the third argument is options
479+
if (typeof callback === "object") {
480+
options = callback;
481+
callback = undefined;
482+
}
483+
484+
if (!callback) {
485+
return new Promise(function(resolve) {
486+
fixWebmDuration(blob, duration, resolve, options);
487+
});
488+
}
489+
478490
try {
479491
var reader = new FileReader();
480492
reader.onloadend = function() {
@@ -492,5 +504,7 @@
492504
} catch (ex) {
493505
callback(blob);
494506
}
495-
};
507+
}
508+
509+
return fixWebmDuration;
496510
});

0 commit comments

Comments
 (0)