2017-05-08 54 views
0

請原諒我的noobness,但爲什麼這不工作? then()永遠不會被解僱,也不會是error()。承諾似乎永遠不會解決。Bluebird Promisify execFile無法承諾解決

任何指針讚賞。謝謝。

var Promise = require('bluebird'); 
var execFile = require('child_process').execFile; 
execFile = Promise.promisify(execFile); 
var IMAGE_DIR = "resources/assets/images"; 
var validImages = ['.jpg', '.png']; 

... // setup omitted ... 

execFile('find', [IMAGE_DIR], function (err, stdout, stderr) { 
    var images = []; 
    return new Promise(function(resolve) { 
    var fileList = stdout.split('\n'); 
    images = fileList.filter(function (image) { 
     var ext = path.extname(image); 
     if (validImages.indexOf(ext) > -1) { 
     return image; 
     } 
    }) 
    return resolve(images); 
    }) 
}).then(function() { 
    console.log(arguments); 
}).catch(console.log.bind(console)); 
+0

您不能將回調傳遞給promisfied函數。你不應該自己調用'new Promise'構造函數。 – Bergi

+0

謝謝您的評論,但這並不能幫助我。 – Simon

回答

3

您只是沒有正確使用execFile()的promisified版本。

你應該做的事:

const Promise = require('bluebird'); 
const execFile = Promise.promisify(require('child_process').execFile); 

execFile('find', [IMAGE_DIR]).then(function(stdout) { 
    // process result here 
}).catch(function(err) { 
    // handle error here 
}); 

如果你需要同時訪問stdoutstderr,那麼你必須選擇通過multiArgs到.promisify()

const Promise = require('bluebird'); 
const execFile = Promise.promisify(require('child_process').execFile, {multiArgs: true}); 

execFile('find', [IMAGE_DIR]).then(function(args) { 
    let stdout = args[0]; 
    let stderr = args[1]; 
    // process result here 
}).catch(function(err) { 
    // handle error here 
}); 
+0

感謝您花時間回答我的問題。 – Simon

2

我非常感謝jfriend000給出的答案。無論如何,如果你想要一個異步等待的ES7解決方案:

const Promise = require('bluebird'); 
const execFile = Promise.promisify(require('child_process').execFile 

const find = async() => { 
    try{ 
     let output = await execFile('find', [IMAGE_DIR]); 
     // handle your output with the variable 
    } catch(error) { 
     // handle your errors here 
    } 
}