簡體   English   中英

Node.js如何在錯誤回調時重新啟動Async.Series

[英]Node.js How to restart Async.Series on error callback

我在應用程序中使用異步實用程序模塊 我有個問題。 當“ 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連接斷開時,我需要以一定的時間間隔重試與服務器的連接

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);
};

使用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
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM