Node.js如何在错误回调时重新启动Async.Series

问题描述 投票:0回答:2

我在我的应用程序中使用Async utility module。我有个问题。当“get_data”阶段返回错误时,如何重新启动async.series?

function get() {
    console.log('App start');
    async.series([
        open_db,
        get_data,
        close_db
    ], function (err) {
        console.log('App down');
    })
};

function open_db(callback) {
    mongoose.connect('mongodb://localhost/app', function (err) {
        if (err) throw err;
        console.log('App connect to DB');
        callback();
    });
};


function get_data(callback) {
    if (err) {
        console.log('Error')
        callback();
    } else {
       console.log('Ok');
       callback();
    }
};


function close_db(callback) {
    mongoose.disconnect(function() {
        console.log('App disconnect from DB');
        callback();
    });
};

在“get_data”阶段,我使用websockets.subscribe操作,并将数据从另一台服务器保存到DB。当websocket连接断开时,我需要以一定的时间间隔重试与服务器的连接

javascript node.js async.js
2个回答
0
投票
function query_data() {
    async.series([
        open_db,
        get_data,
        close_db
    ], function (err) {
        if (err)
            ...
    })
};

function open_db(callback, attempt_no) {
    mongoose.connect('mongodb://localhost/app', function(err) {
        if (!err)
            return callback();

        attemp_no = !attempt_no ? 1 : attempt_no + 1;

        if (attempt_no > 5)
            return callback(new Error('Maximum number of attempts exceeded'));

        setTimeout(() => open_db(callback, attempt_no), 500);
    });
};

function get_data(callback) {
    if (err) 
        return callback(err);

    // do-smth-with-data and call callback
};

function close_db(callback) {
    mongoose.disconnect(callback);
};

0
投票

使用async.retry

function all_get_data(cb) {
    console.log('App start');
    async.series([
        open_db,
        get_data,
        close_db
    ], function (err) {
        if (err) { 
            console.log('App down');
            return cb(err)
        }
        return cb()
    })
};

// try calling apiMethod 3 times, waiting 200 ms between each retry
async.retry({times: 3, interval: 200}, all_get_data, function(err, result) {
    // do something with the result
});
© www.soinside.com 2019 - 2024. All rights reserved.