[英]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命令执行得太早了。
我虽然那是承诺和.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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.