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处理程序.

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...