将回调代码转换为promise

时间:2015-07-28 08:28:49

标签: node.js promise bluebird

我想使用蓝鸟图书馆,我的问题是如何将以下代码转换为蓝鸟承诺

var exec = require('child_process').exec;
var cmd = 'npm install morgan --save';

exec(cmd, function(error, stdout, stderr) {
    if(error || stderr){
        console.error(error);
        console.error(stderr);
        console.log("test");
    }
});

2 个答案:

答案 0 :(得分:2)

不要使用promise构造函数。请。我已经失去了几十个小时调试代码,人们错过了这只是一件事

Bluebird很乐意自动为您宣传,它会更快地完成任务并使其更容易调试。

var Promise = require("bluebird");
var exec = Promise.promisify(require('child_process').exec);
var cmd = 'npm install morgan --save';
exec(cmd).spread(function(stdout, stderr){
    // access output streams here    
    console.log(stdout, stderr); // output both stdout and stderr here
}).catch(function(error){
    // handle errors here
});

在未来,我们有一个规范的参考,将事物转化为承诺。还有一个list of how-tos here

答案 1 :(得分:0)

非常简单,只需使用bluebird promise构造函数:

var Promise = require("bluebird");
var exec = require('child_process').exec;
var cmd = 'npm install morgan --save';

var promise = new Promise(function(resolve, reject){
    exec(cmd, function(error, stdout, stderr) {
        if(error || stderr)   return reject(error || stderr);  
        return resolve(stdout);
    }); 
});


promise
  .then(console.log.bind(console))      //success handler
  .catch(console.log.bind(console))     // failure handler