【问题标题】:nodeJS: chaining exec commands with promisesnodeJS:用承诺链接 exec 命令
【发布时间】:2015-04-17 20:27:36
【问题描述】:

我正在使用 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 命令执行得太早了。

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

我早就料到会发生这种情况:

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

【问题讨论】:

    标签: javascript node.js promise q


    【解决方案1】:

    这就是你的问题:

    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));
    

    【讨论】:

    • 或者,.then(this.executeCommand.bind(this, 'screencapture ' + path))
    猜你喜欢
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 2018-01-02
    • 2020-04-24
    • 1970-01-01
    • 2015-04-15
    相关资源
    最近更新 更多