【发布时间】: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