Last active
July 4, 2020 20:33
-
-
Save hdvianna/bab457de44f66908eda01bb7660bad7a to your computer and use it in GitHub Desktop.
JS Async Function Queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function f1(next) { | |
setTimeout(function() { | |
console.log("1"); | |
next.dequeue(); | |
}, 500); | |
} | |
function f2(next) { | |
setTimeout(function() { | |
console.log("2"); | |
next.dequeue(); | |
}, 1000); | |
} | |
function f3(next) { | |
console.log("3"); | |
next.dequeue(); | |
} | |
function f4(next) { | |
setTimeout(function() { | |
console.log("4"); | |
next.dequeue(); | |
}, 5000); | |
} | |
function f5(next) { | |
setTimeout(function() { | |
console.log("5"); | |
next.dequeue(); | |
}, 700); | |
} | |
window.AsyncFunctionQueue = function (onsuccess, onerror) { | |
var q = []; | |
var qstate = "STOPPED"; | |
var completed = function () { | |
onsuccess(); | |
qstate = "STOPPED"; | |
} | |
this.enqueue = function(f) { | |
var qlen = q.length; | |
var i = { | |
f: f, | |
dequeue: function() { | |
var next = (this.next)?this.next:{dequeue:completed, error:onerror} | |
this.f(next); | |
q.shift(); | |
}, | |
error: function(error) { | |
onerror(error); | |
} | |
}; | |
q.push(i); | |
if (qlen > 0) { | |
q[qlen-1].next = i; | |
} | |
return this; | |
} | |
this.go = function() { | |
if (qstate == "STOPPED") { | |
qstate= "RUNNING"; | |
if (q.length > 0) { | |
q[0].dequeue(); | |
} else { | |
completed(); | |
} | |
} else { | |
throw new Error("Queue already started."); | |
} | |
} | |
} | |
var q = new AsyncFunctionQueue(function() {console.log("completed!")}, function(error) {console.log(error)}); | |
q.enqueue(f1).enqueue(f2).enqueue(f3).enqueue(f4).enqueue(f5).go(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah, I know Promises. This is an old script from when I just wanted to make my own async function synchronization "API". =P