nodeJS:使用 promises 链接 exec 命令

nodeJS: chaining exec commands with promises

我正在使用 nodeJS 来链接两个 exec 调用。我想等待第一个完成,然后再进行第二个。我为此使用 Q

我的实现是这样的:

我有一个 executeCommand 函数:

executeCommand: function(command) {
    console.log(command);
    var defer = Q.defer();
    var exec = require('child_process').exec;

        exec(command, null, function(error, stdout, stderr) {
            console.log('ready ' + command);
            return error 
                ? defer.reject(stderr + new Error(error.stack || error))
                : defer.resolve(stdout);
        })

        return defer.promise;
}

还有一个 captureScreenshot 函数,它链接前一个调用的两个调用。

captureScreenshot: function(app_name, path) {
        return this.executeCommand('open -a ' + app_name)
            .then(this.executeCommand('screencapture ' + path));
}

当我执行 captureScreenshot('sublime', './sublime.png) 时,日志输出如下:

open -a sublime
screencapture ./sublime.png
ready with open -a sublime
ready with screencapture ./sublime.png

有人可以解释为什么不等到第一个命令(open -a sublime)执行完成后才执行第二个命令(screencapture)吗?当然,我没有得到我想切换到的应用程序的屏幕截图,因为 screencapture 命令执行得太早了。

虽然这就是 promises 和.then-chaining 的全部意义..

我本以为会发生这种情况:

open -a sublime
ready with open -a sublime
screencapture ./sublime.png
ready with screencapture ./sublime.png

这就是你的问题:

return this.executeCommand('open -a ' + app_name)
   .then(this.executeCommand('screencapture ' + path));

您基本上已经执行了 this.executeCommand('sreencapture'...),而事实上,您实际上想在先前的承诺解决时推迟它的执行。

尝试重写它:

return this.executeCommand('open -a ' + app_name)
    .then((function () { 
        return this.executeCommand('screencapture ' + path);     
     }).bind(this));