0

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')`
  • See here: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call . The best solution, IMO, is to return a Promise. – Paul Apr 21 '16 at 22:10
  • Thanks, but unfortunately PhantomJS does not support Promises. –  Apr 21 '16 at 22:14
  • Then you'll have to use one of the other solutions in that answer or a library that implements Promises like `bluebird`, or upgrade to a newer version of JavasScript that has builtin Promises. – Paul Apr 21 '16 at 23:08

0 Answers0