Return from function after chain of callbacks

时间:2016-04-21 22:09:08

标签: javascript

I am making something like scenario object for PhantomJS. Here are my object representing scenario, which shall execute sequentially set of steps one after another. But i want to have scenario "run" function to return to main body only after the last step is finished since it will be called by external object via array loop in the same manner (e.g. one scenario shall be executed after previous finish).

P.S. Ping function is just a stub, which represents call to "system" function with only callback.

Javascript

"use strict"

function ping(host, callback) {
    setTimeout(function() {
        callback(host);
    }, 100);
}

var scenario = {
    index: 0,
    timer: null,
    ready: true,
    run: function() {
        var $ = this;
        this.timer = setInterval(function run_step() {
            if ($.is_ready()) {
                if ($.index < $.steps.length) {
                    $.block();
                    $.steps[$.index].run($);
                } else {
                    $.stop();
                }
            }
        }, 50);
    },
    stop: function() {
        if (this.timer !== null) {
            clearInterval(this.timer);
        }
        console.log('stop');
    },
    is_ready: function() {
        return this.ready;
    },
    block: function() {
        this.ready = false;
        console.log('block');
    },
    next: function() {
        this.index++;
        this.ready = true;
        console.log('free');
    },
    steps: [{
        run: function($) {
            console.log('step1');
            ping('yandex.ru', function(stdout) {
                console.log(stdout);
                $.next();
            })
        }
    }, {
        run: function($) {
            console.log('step2');
            ping('lenta.ru', function(stdout) {
                console.log(stdout);
                $.next();
            })
        }
    }, {
        run: function($) {
            console.log('step3');
            ping('habrahabr.ru', function(stdout) {
                console.log(stdout);
                $.next();
            })
        }
    }]
}

console.log('start')
scenario.run();
console.log('end')`

0 个答案:

没有答案