Write a library in javascript that can run asynchronous functions sequentially

132 views Asked by At

I want to write a library in javascript that can run the code like this:

seq.next(function(done){
  setTimeout(done,3000);
}).next(function(done){
  setTimeout(function(){
    console.log("hello");
    done();
  },4000);
}).end(); //.next morever

Actually I want to write a library that can excecute asynchronous functions in order(sequentially). Each asynchronous function should run the "done" function on its end.

Could anyone please help me. Thanks very much!

1

There are 1 answers

3
Mohammad Reza Dehghani Tafti On BEST ANSWER

The library is:

var seq = (function () {

var myarray = [];
var next = function (fn) {
    myarray.push({
        fn: fn 
    });
    // Return the instance for chaining
    return this;
};

var end = function () {
    var allFns = myarray;

    (function recursive(index) {
        var currentItem = allFns[index];


        // If end of queue, break
        if (!currentItem)
            return;

        currentItem.fn.call(this, function () {
            // Splice off this function from the main Queue
            myarray.splice(myarray.indexOf(currentItem), 1);
            // Call the next function
            recursive(index);
        });
    }(0));
    return this;
}

return {
    next: next,
    end: end
};
}());

And the use of this library is sth like this:

seq.next(function (done) {
            setTimeout(done, 4000);
        }).next(function (done) {
            console.log("hello");
            done();
        }).next(function (done) {
            setTimeout(function () {
                console.log('World!');
                done();
            }, 3000);
        }).next(function (done) {
            setTimeout(function () {
                console.log("OK");
                done();
            }, 2000);
        }).end();