为什么我不能用bluebird的Promise.method替换trycatch库?

时间:2014-11-03 21:29:31

标签: node.js promise bluebird

所以我想我可以使用bluebird的Promise.method()替换我一直在使用的trycatch lib。

不幸的是,它似乎没有从setTimeout中捕获抛出的错误。

我有这些方面的东西

function run()
{
    var p = Promise.pending()

    var inner = Promise.method(function()
    {
        //some code that could potentially get stuck

        setTimeout(function $timeoutTaskKill() {
            if (p.promise.isPending())
            {
                var duration = moment.duration(taskTimeout).seconds();
                throw new Error(util.format('timeout has been reached: %ss', duration));
            }
        }, taskTimeout)
    });

    //pseudo
    inner().then(p.reject, p.resolve);

    return p.promise;
}

它崩溃了我的过程。当我使用trycatch库而不是Promise.method时,它捕获了错误。

1 个答案:

答案 0 :(得分:2)

trycatch使用domains来捕获此类错误,承诺不会。

要获得被拒绝的承诺,您需要明确地这样做。这可能是throw来自promise(then)处理程序,但不是来自任意异步回调。

你能做什么:

  • 实际上拒绝来自回调的承诺:

    setTimeout(function $timeoutTaskKill() {
        var duration = moment.duration(taskTimeout).seconds();
        p.reject(new Error(util.format('timeout has been reached: %ss', duration)));
    }, taskTimeout)
    
  • 使用承诺。始终在最低级别进行宣传,在这种情况下为setTimeout。实际上,Bluebird已经为您完成了这项工作:Promise.delay

    Promise.race([
        actualToDo(),
        Promise.delay(taskTimeout).then(function() {
            var duration = moment.duration(taskTimeout).seconds();
            throw new Error(util.format('timeout has been reached: %ss', duration));
        })
    ])
    
  • 或使用Bluebird的内置timeout() method

相关问题