微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

node.js – 中途停止承诺链

嘿伙计们,我正试图中途停止承诺链(捕获后).因此,在第一个承诺发生错误后,catch将捕获它,但我不希望链继续.我正在使用蓝鸟.我该怎么做?

getRedirectedURL(url).then(function(url) {
                console.log(1);
                url = domainCleanse(url);
                sql = MysqL.format(select,url);

                return [ url,MysqLQuery(sql) ];

            }).catch(function(error) {
                console.log(2);
                console.error(error);
                socket.emit('error:unreachable',url + ' was unreachable');
            }).spread(function(url,rows) {
                console.log(3);
                if(_.isEmpty(rows[0])) {
                    socketList.push({
                        url: url,ttl: _.Now(),socket: socket,added: false
                    });
                } else {
                    socket.emit('done',mapResults(rows[0]));
                }
            }).catch(function(error) {
                console.log(4);
                console.error(error);
                socket.emit('error','We Could not reach ' + url + ' at this time.');
            });

解决方法

概括您的示例,它看起来像这样:

promisetoFoo()
    .then(promisetoBar)
    .catch(FailedToFooOrBar)
    .then(promisetoFrob)
    .catch(FailedToFrob)

沿着幸福的道路,你向Foo承诺,然后到Bar,然后到Frob.根据您的描述,您希望处理错误Fooing或Barring与错误Frobbing分开处理.因此,一个简单的解决方案是将Frob的错误处理埋没到该承诺中.因此,你没有将对Frob的承诺链接起来,而是将Frob的承诺链接起来并处理Frobbing中的错误.像这样的东西:

promisetoFoo()
    .then(promisetoBar)
    .catch(function (error) {
        FailedToFooOrBar(error);
        return Promise.reject(error);
    })
    .then(function (x) {
        return promisetoFrob(x).catch(FailedToFrob);
    });

关键是要确保第一个捕获中的on-reject处理程序最终在离开时使链处于拒绝状态.这是在上面的示例中通过从处理程序返回被拒绝的Promise来处理的.您也可以通过从处理程序中抛出一个错误来处理它.如果你不做其中的一件事,那么当处理程序完成时,promise将处于一个完成状态,并且将调用后续调用提供的on-fulfill处理程序.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐