在bluebird promise中等待可选的进程操作

时间:2016-04-13 23:11:38

标签: javascript node.js promise bluebird

我有bluebird promise,它会运行支票。如果此检查为真,则可以继续。但是,如果此检查为false,则需要spawn一个异步进程,它必须等待完成才能继续。

我有以下内容:

var foo = getPromise();

foo.spread( function (error, stdout, stdin) {
    if (error) {
        // ok, foo needs to hold on until this child exits
        var child = spawn(fixerror);
        child
            .on('error', function (e) {
                //I need to error out here
            })
            .on('close', function (e) {
                //I need to have foo continue here
            });
    } else {
        return "bar";
    }
});

我将如何做到这一点?

2 个答案:

答案 0 :(得分:1)

首先,为什么您的.spread()处理程序将error作为第一个参数进行回调。这似乎不正确。错误应该导致拒绝,而不是履行。

但是,如果这确实是您的代码的工作方式,那么您只需要在.spread()处理程序中返回一个promise。那个承诺将被束缚到最初的承诺,然后你可以看到两者都完成了:

getPromise().spread( function (error, stdout, stdin) {
    if (error) {
        // ok, foo needs to hold on until this child exits
        return new Promise(function(resolve, reject) {
            var child = spawn(fixerror);
            child.on('error', function (e) {
                //I need to error out here
                reject(e);
            }).on('close', function (e) {
                // plug-in what you want to resolve with here
                resolve(...);
            });
         });
    } else {
        return "bar";
    }
}).then(function(val) {
    // value here
}, function(err) {
    // error here
});

但是,您的.spread()处理程序可能不应该在那里有error参数,而是应该拒绝原来的承诺:

getPromise().spread( function (stdout, stdin) {
    // ok, foo needs to hold on until this child exits
    return new Promise(function(resolve, reject) {
        var child = spawn(fixerror);
        child.on('error', function (e) {
            //I need to error out here
            reject(e);
        }).on('close', function (e) {
            // plug-in what you want to resolve with here
            resolve(...);
        });
    });
}).then(function(val) {
    // value here
}, function(err) {
    // error here
});

答案 1 :(得分:1)

在promise函数中包装spawn或任何其他替代路由,然后将流保持为,(示例代码):

promiseChain
  .spread((stderr, stdout, stdin) => stderr ? pSpawn(fixError) : 'bar')
  .then(...

// example for promisified spawn code: 
function pSpawn(fixError){
    return new Promise((resolve, reject) => {        
        spawn(fixError)
          .on('error', reject)
          .on('close', resolve.bind(null, 'bar'))        
    })
}