0

I'm trying to use ffmpeg to cut a few seconds of a directory with mp3s. But my actual problems comes with using promises.

Instead of starting one ffmpeg process after the other it starts up one for each file immediately. My guess is the promise isn't waiting for the resolve and I didn't understand it properly.

var P = require('bluebird');
var fs = P.promisifyAll(require("fs"));

function transcode(filename) {
    return P.delay(1000).then(function() {
        console.log(filename);
    });
}
var in_dir = "./somedir/";

var getFiles = function(){
    return fs.readdirAsync(in_dir);
};

getFiles().mapSeries(function(filename){
    transcode(filename);
});
F. Rakes
  • 1,487
  • 3
  • 17
  • 25
  • I tried to answer but after re-reading, I deleted it. Didn't seem right. Can you clarify what the desire output or effect is? It is normal that when using promises (or call backs) they'll start side-by-side. Then you get notifications (via `then`) for the "next step". – Frank V Feb 09 '17 at 20:40
  • I want a sequential approach for each transcode so I don't get hundreds of processes starting at once and have my CPU at 100%. I tried using `.mapSeries()` at the bottom. Or maybe have a queue of max 5 processes? – F. Rakes Feb 09 '17 at 20:49
  • 1
    Avoid the [`Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! Put only the `ffmpeg().…` chain in the constructor callback, but not the `getDuration(in_file)` promise. – Bergi Feb 09 '17 at 21:18
  • I'm guilty of using that anti-pattern because it seemed easiest, thanks for looking out. – F. Rakes Feb 09 '17 at 21:22
  • 1
    **Run bluebird with warnings on** the library can actually automatically identify these "missing return" bugs and let you know exactly where they happened. – Benjamin Gruenbaum Feb 09 '17 at 21:23

1 Answers1

1

I've created a simplified version of your code. The only missing thing was the return statement for the final closure:

var P = require('bluebird');
var fs = P.promisifyAll(require("fs"));

function transcode(filename) {
    return P.delay(1000).then(function() {
        console.log(filename);
    });
}
var in_dir = "./somedir/";

var getFiles = function(){
    return fs.readdirAsync(in_dir);
};

getFiles().mapSeries(function(filename){
    return transcode(filename);
});
Sébastien
  • 1,015
  • 8
  • 7
  • I'll edit my question to your simplified code (with my error) so that other people might find it more useful in the future – F. Rakes Feb 09 '17 at 21:17