node.js - Async.js 跳出系列

标签 node.js async.js

我用的是草兰的辉煌Async.js 。我正在执行一系列功能。在第一个函数中,我有一个条件,应该跳过该系列的所有其余函数并直接转到最终回调:

async.series([
    function one (next) {
        if(!condition) {
            // skip all the other functions and go to final callback
        }
        // do stuff
        return next();
    },
    function two (next) {
        // do stuff
        return next();
    },
    function three (next) {
        // do stuff
        return next();
    }
], function (err) {
    // final callback stuff
});

因此,如果函数中不满足一个条件,则直接转到最终回调。

Async series docs状态

If any functions in the series pass an error to its callback, no more functions are run, and callback is immediately called with the value of the error.

但是抛出错误对我来说看起来并不是一个干净的方法。为了能够在最终回调中正确处理“真实”错误,我必须引入一个假错误......还有其他干净的方法吗?

最佳答案

目前我是如何解决这个问题的。我确实抛出了一个特定的错误来跳过本系列的其余部分,从最终回调中的一般错误处理中排除此特定错误:

    async.series([
        function one (next) {
            if(!condition) {
                return next('condition_not_met');
            }
            return next();
        },
        function two (next) {
            // this isn't executed if condition isn't met in function one
            return next();
        }
    ], function (err) {
        if (err && err !== 'condition_not_met') {
            // general error handling
        }
        // do more stuff
    });

如果这是 async.series 的使用方式,或者是否有更优雅的方式来处理我的场景,我仍然感兴趣。干杯。

关于node.js - Async.js 跳出系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28220279/

相关文章:

javascript - 如何使用 $.getJSON 编写异步?

javascript - net.socket.setTimeout 不适用于 async.eachOfSeries

node.js - 如何使用 NodeJS 检索 MongoDB 中特定的查询数组集合

javascript - 如何等待 async.timeseries()?

使用-g安装插件时node.js npm错误

ruby - 如何在 node.js 中执行此 PKCS7 签名?

javascript - 在 Node.js 的 while 循环内使用 setTimeout

javascript - 对多个 MongoDB 聚合函数使用 Async Parallel

node.js - MongoDB 不使用 NodeJS 驱动程序应用程序返回数据

javascript - Express.js 4 路由与 router.route 不匹配