簡體   English   中英

nodeJS:將promise命令與promise鏈接

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM