working on it ...

Filters

Explore Public Snippets

Sort by

Found 3,734 snippets matching: async

    public by sTiLL-iLL @ SniPitz-KND  550002  5  8  16

    Async Queue in C#

    using System;
    using System.Net;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    
    public class ParalyzKue
    {
    	readonly object _locker = new object();
    	Task _tail = Task.FromResult (true);
    	
    	public Task Enqueue (Action action)
    	{
    		lock (_locker)
    			return _tail = _tail.ContinueWith (ant => action());
    	}
    
    	public Task<TResult> Enqueue<TResult> (Func<TResult> func)
    	{
    		lock (_locker)
    			return (Task<TResult>) (_tail = _tail.ContinueWith (ant => func()));
    	}
    
    	public Task Enqueue (Func<Task> action)
    	{
    		lock (_locker)
    			return _tail = _tail.Catch().Then (action);
    	}	
    
    	public Task<TResult> Enqueue<TResult> (Func<Task<TResult>> func)
    	{
    		lock (_locker)
    			return (Task<TResult>) (_tail = _tail.Catch().Then (func));
    	}
    }
    
    
    public static class Extensions
    {
    	public static Task<T> Catch<T,TError> (this Task<T> task, Func<TError,T> onError) where TError : Exception
    	{
    		var tcs = new TaskCompletionSource<T> ();
    		task.ContinueWith (ant => {
    			if (task.IsFaulted && task.Exception.InnerException is TError)
    			{
    				tcs.SetResult (onError ((TError) task.Exception.InnerException));
    			}
    			else if (ant.IsCanceled)
    			{
    				tcs.SetCanceled ();
    			}
    			else if (task.IsFaulted)
    			{
    				tcs.SetException (ant.Exception.InnerException);
    			}
    			else
    			{
    				tcs.SetResult (ant.Result);
    			}
    		});
    		return tcs.Task;
    	}		
    	public static Task<T> Catch<T,TError> (this Task<T> task, T onError) where TError : Exception
    	{
    		return task.Catch<T,TError> (ex => onError);
    	}
    	
    	public static Task<T> Catch<T,TError> (this Task task, T onError) where TError : Exception
    	{
    		return task.ToTaskOfT<T>().Catch<T,TError> (onError);
    	}
    
    	public static Task Catch (this Task task)
    	{
    		return task.Catch<object,Exception> (null);
    	}
    	
    	public static Task<T> Catch<T> (this Task<T> task, T valueIfError = default(T))
    	{
    		return task.Catch<T,Exception> (valueIfError);
    	}
    
    	public async static Task<T> ToTaskOfT<T> (this Task t)
    	{
    		await t;
    		return default(T);
    	}
    	
    	public static async Task Then(this Task task, Func<Task> continuation)
    	{
    		await task;
    		await continuation();
    	}
    	
    	public static async Task<TNewResult> Then<TNewResult>(this Task task, Func<Task<TNewResult>> continuation)
    	{
    		await task;
    		return await continuation();
    	}
    	
    	public static async Task Then<TResult>(this Task<TResult> task, Func<TResult,Task> continuation)
    	{
    		await continuation(await task);
    	}
    	
    	public static async Task<TNewResult> Then<TResult, TNewResult>(this Task<TResult> task, Func<TResult, Task<TNewResult>> continuation)
    	{
    		return await continuation(await task);
    	}
    }
    
    /*
    public void doKue()
    {
    	var pcQ = new ParaKue();
    	
      pcQ.Enqueue (() => AsyncMethod1 ("http://www.rotten.com/")).Dump ("Task 1");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/")).Dump ("Task 2");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://yahoo.com/search?q=the cube")).Dump ("Task 3");
      pcQ.Enqueue (() => AsyncMethod1 ("http://www.rotten.com/")).Dump ("Task 4");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/")).Dump ("Task 5");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://www.google.com/search?q=web scrapers")).Dump ("Task 6");
      pcQ.Enqueue (() => AsyncMethod1 ("http://www.rotten.com/")).Dump ("Task 7");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/")).Dump ("Task 8");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/search?q=aliens gods")).Dump ("Task 9");
      pcQ.Enqueue (() => AsyncMethod ("http://www.rotten.com/")).Dump ("Task 10");
    	pcQ.Enqueue (() => AsyncMethod ("https://youtube.com/")).Dump ("Task 11");
    	pcQ.Enqueue (() => AsyncMethod ("https://www.google.com/search?q=javascript")).Dump ("Task 12");
      pcQ.Enqueue (() => AsyncMethod ("http://www.rotten.com/")).Dump ("Task 13");
    	pcQ.Enqueue (() => AsyncMethod ("https://youtube.com/search?q=aliens")).Dump ("Task 14");
      pcQ.Enqueue (() => AsyncMethod ("https://www.yahoo.com/")).Dump ("Task 15");
    	pcQ.Enqueue (() => AsyncMethod ("https://youtube.com/")).Dump ("Task 16");
    	pcQ.Enqueue (() => AsyncMethod ("https://www.google.com/search?q=aliens disclosure")).Dump ("Task 17");
    }
    
    string SyncMethod (string uri)
    {
        var x = new System.Net.WebClient();
        var y = x.DownloadString(uri);
        return y;
    }
    
    async Task<string> AsyncMethod (string uri)
    {
       return await Task.Run(() => new System.Net.WebClient().DownloadStringTaskAsync(uri).Dump());
    }
    
    
    async Task<string> AsyncMethod1 (string uri)
    {
       var x = await new System.Net.WebClient().DownloadStringTaskAsync(uri);
       return x;
    }
    
    */

    public by sTiLL-iLL @ SniPitz-KND  532551  3  8  21

    Ajax again?? Wrap it!! XHR Agent 4Ya

    XHR wrapper! object pooling and cueing!!! EveryOneZ dOing IT!
    
    var myXHR = {
           ESpec: function (wrap, evt) {
               return { xhrWrap: wrap, event: evt };
           },
           Agent: function(maxConnect) {
               var bCued = [], slf = this,
                   max = maxConnect || 3;
                   this.curCon = 0;
               function inCue() {
                   if (self.bCued < max) {
                       self.bCued++;
                       var itm = is.Readied.shift();
                       itm.evt.addEventListener(['EVENT_COMPLETE'], 
                         function (e) {
                             self.bCued--;
                             if (this.Readied.length !== 0) {
                               inCue();
                             }
                         });
                       itm.wrap.call(itm, args, itm.evt);
                    }
               }
               this.Readied = function (ESpec) {
                   bCued.push(ESpec);
                   inCue();
                   return ESpec.evt;
               };
            }
       };
    
                

    public by sTiLL-iLL  203282  1  8  27

    kWetntz.js ... next in line please...

    sequential async execution... NEXT!!! *** idk if this even werks, havent tried yet! ***
    //  sequential execution....
    
    var kWentz = (function() {
        var roster = {}, lastTime = {}, slf = this,
            signal = function(name, arg) {
               var idx=0, kall = {};
               if(roster[name]) {
                   for(idx; kall=roster[name][idx]; idx++) {
                       kall(arg);
                   }
               }
            },
            receive = function(name, receiver) {
               if(!roster[name]) {
                  roster[name] = [];
               }
               roster[name].push(receiver);
               return slf;
            },
            drop = function(name, receiver) {
               if(roster[name]) {
                   var lst = [], kall = {}, idx = 0;
                   for(idx; kall=roster[name][idx]; idx++) {
                       if(kall !== receiver) {
                           lst.push(kall);
                       }
                   }
                   roster[name] = lst;
               }
               return slf;
            },
            exec = function() {
              if(arguments.length > 0) {
                var cbks = [], kall = {}, elm = {}, idx = 0;
                for(idx; kall=arguments[idx]; idx++) {
                   cbks.push(kall);
                }
                elm = cbks.shift();
                if(typeof elm === 'function') {
                   elm(lastTime, function(dta) {
                         lastTime = dta;
                         exec.apply(slf, cbks);
                   });
                } 
                else if(typeof elm === 'object' && elm.length > 0) {
                   var kall = elm.shift(),
                      callBK = function(dta) {
                         lastTime = dta;
                         exec.apply(slf, cbks);
                      };
                   kall.apply(kall, elm.concat([callBK]));
                }
             } 
             else {
                  signal("done", lastTime);
             }
             return slf;
          };
          return {
              execute: exec,
              receive: receive,
              drop: drop
          };
    })();            

    public by sTiLL-iLL @ SniPitz-KND  4521  2  7  10

    PROMISE! X(ml) 2 J(son)!

    makE XML PROMISE to be JSON DEFERRED....
    var xp = (function(){
       var Promise = function () {
      		return {
      			status: 'pending',error: null,
      			posCBKs: [],negCBKs: [],
      			then: function (posCBK, negCBK) {
      				var defer = new Deferred();
      				posCBK=(!posCBK)?function(d){d=(d||true);return d;}:posCBK;
      				negCBK=(!negCBK)?function(d){d=(d||true);return d;}:negCBK;
      				this.posCBKs.push({
      					func: posCBK,
      					deferred: defer
      				});				
      				this.negCBKs.push({
      					func: negCBK,
      					deferred: defer
      				});
      				if (status == 'resolved') {
      					this.execAction({
      						func: posCBK,
      						deferred: defer
      					}, this.data);
      				} else if (status == 'rejected') {
    					this.execAction({
      						func: negCBK,
      						deferred: defer
      					}, this.error);
      				}
      				return defer.promise;
      			},
      			execAction: function (callbackData, result) {
      				setTimeout(function () {
      					var res = callbackData.func(result);
      					if (res instanceof Promise) {
      						callbackData.deferred.bind(res);
      					} else {
      						callbackData.deferred.resolve(res);
      					}
      				}, 0);
      			}
      		};
      	},
        Deferred=function () {
      	  return {
      	  	promise: new Promise(),
      		  resolve: function (data) {
      			  var pms = this.promise;
      			  pms.data = data;
      			  pms.status = 'resolved';
      		  	if (pms.posCBKs) {
      			  	pms.posCBKs.forEach(function (dta) {
      					pms.execAction(dta, data);
      				});
      			}
      		},
      		reject: function (err) {
      			var pms = this.promise;
      			pms.error = err;
      			pms.status = 'rejected';
      			if (pms.negCBks) {
      				pms.negCBKs.forEach(function (dta) {
      					pms.execAction(dta, err);
      				});
      			}
      		},
      		bind: function (promise) {
      			var slf = this;
      			promise.then(function (dta) {
      				slf.resolve(dta);
      			}, function (err) {
      				slf.reject(err);
      			});
      		}
      	};
      }; // XML to JSON module 
      var xj = function(xml) {
        	var i=0,xJsn={},len={};
        	if (xml.nodeType == 1) {
        		if (xml.attributes.length > 0) {
        		  len = xml.attributes.length;
        		  xJsn["@attributes"] = {};
        			for (;;++i<len) {
        				var xAItm = xml.attributes.item(i);
        				xJsn["@attributes"][xAItm.nodeName] = xAItm.nodeValue;
        			}
        		}
        	}
        	else if(xml.nodeType == 3) {
        		xJsn = xml.nodeValue;
        	}
        	if (xml.childNodes) {
        	  i=0,len=xml.childNodes.length;
        		for(;;++i<len) {
        			var xnd = xml.childNodes.item(i),
        			    xndNm = xnd.nodeName;
        			if (!xJsn[xndNm]) {
        				xJsn[xndNm] = xmlToJson(xnd);
        			} else {
        				if (!xJsn[xndNm].push) {
        					var orig=xJsn[xndNm];
        					xJsn[xndNm]=[];
        					xJsn[xndNm].push(orig);
        				}
        				xJsn[xndNm].push(X2J(xnd));
        			}
        		}
        	}
        	return xJsn;
        };
        return {
            x2j: function(xml, func) {
              var dfd = new Deferred();
              try {
                 var rezlt = xj(xml);
                 dfd.resolve(rezlt);
                 if(func) {
                   func(rezlt);
                 }
              }
              catch(er) {
                 dfd.reject(er);
              }
              return dfd.promise;
            }
        };
    }());                        

    public by cghersi  3408  1  6  0

    How to create an asynchronous task in C#

    This is a simple way to create a task that will run asynchronously with respect to the current thread
    System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
      log.Info("This will run async");
    });
    

    public by sTiLL-iLL @ SniPitz-KND  4456  9  8  36

    Make anything a SignlSEE broadcasting transmitter

    create observables for pubsub, or home-spun MVcwWCvvV666. The kids will eat their vegies and grandma finaly went to bed! Its a great conversation starter!
    
      // OBSERVE ME!!!!
    
    var SeeMe=(function(obj) {
    	var watchd={},mod1=obj||{};
    	function Model (mod1) {
    		this.base = mod1;
    		this.get = function(k) {
    			if (k) {
    				var u = this.base;
    				return u[k];
    			}
    			else {
    				var uu = this.base;
    				return uu;
    			}
    		};
    	}
    	watchd = Model;
    	watchd.prototype = Signals;
    	watchd.prototype.on = function(v, cbk) {
    		this.receive(v, function(d) {
    			cbk.call(this.base, d);
    		});
    	};
    	watchd.prototype.emit = function(v) {
    		this.signal("change", v);
    	};
    	watchd.prototype.off = function(v) {
    		this.drop(v);
    	};
    	watchd.prototype.set = function(k, v) {
    		if (v && v !== this.base[k]) {
    			if (v==Array||v!=Array&&k!=Array) {
    				this.base[k]=v;
    			} else if(v==Array) {
    				this.base[k].push(v);
    			}
    			this.signal("change", this.base);
    		}
    	};
      watchd = new watchd(mod1);
    	return watchd;
    }(Signals));
    
    
    var user = {
    		name1: "Richard",
    		name2: "Longwood",
    		occupation: "Software Engineer",
    		age: 40,
    		title: 'User!',
    		subTitle: "Edit Me!",
    		canEdit: true,
    		skills: ["ajax", "css", "javascript", "HTML5"]
    	};
    
    
    // Create an instance of our new type....
    
    SeeMe.base = user;
    var User = Object.create(SeeMe);
    
    
    // Now we'll see that the values are set and accessable
    
    User.get(); // Object {name1: "Richard", name2: "Longwood", occupation: "Software Engineer", age: 40, title: "User!"…}
    
    User.get("skills"); // ["ajax", "css", "javascript", "HTML5"]
    
    
    User.set("skills","blah");
    
    User.get("skills"); // "blah"
    
    
    User.set("skills",["ajax", "css", "javascript", "HTML5"]);
    
    User.get("skills");  //  ["ajax", "css", "javascript", "HTML5"]
    
    User.get("skills")[2];  // "javascript"
    
    
    User.set("skills",[1,2,3]); 
    
    User.get("skills");  // [1, 2, 3]
    
    
    /* 
        Now the kewl part... 
        lets wire up a signal channel to
        fire an alert whenever our User is changed...
    */
    
    User.on("change", function(d) {
        alert(JSON.stringify(d));
    });
    
    
    
    // Now we'll reassign them and watch our alerts go BOING!
    
    User.set("age", "OlD");
    User.set("name1", "HEaTH");
    User.set("name2", "DERN!");
    User.set("title", "who kares");
    User.set("subTitle", "whatever");
    User.set("occupation", "coding");
    User.set("skills", [1,2,3,4,5,6,7,8,9,0]);
    
    
    // Just to make sure the new values were pesisted...
    
    User.get();
    User.get("age");
    User.get("name1");
    User.get("name2");
    User.get("title");
    User.get("subTitle");
    User.get("occupation");
    User.get("skills");
    
    
    /* 
       The modules arent in the correct order of dependancy, 
       but I wanted the newest part to be featured. Below is my
       Signals eventing system. The module at the top, 
       
       SEEKr.... is a signaling, (observable), wrapper that can make
       almost anything a signal transmitter for use in pub-sub, mediator,
       
       whatever you like. theres also a small example just below the
       SEEKr module.
    */
    
    
    var Signals = (function() {
        'use strict';
        var sigCache = {}, singleRtnVal = false, 
        received = function(eventName, func) {
            return wen(eventName, function(evnt) {
                return func(evnt);
            });
        }, 
        dropReceivers = function(eventName, func) {
            if (eventName && func && typeof func === "function") {
                dropReceiver(eventName, func);
                return this;
            }
            if (!eventName) {
                sigCache = {};
                return this;
            }
            if (sigCache && sigCache[eventName]) {
                sigCache[eventName] = null;
            }
            return this;
        }, 
        setSingleRV = function(val) {
            singleRtnVal = val;
            return this;
        }, 
        getSingleRV = function() {
            if (receivers.hasOwnProperty('singleRtnVal')) {
                return singleRtnVal;
            } 
            else {
                return true;
            }
        }, 
        dropReceiver = function(eventName, func) {
            if (sigCache && sigCache[eventName]) {
                var sigLst = sigCache[eventName];
                if (isAry(sigLst)) {
                    var idx = -1;
                    for (var i = 0, l = sigLst.length; i < l; i++) {
                        if (sigLst[i] === func || (sigLst[i].receiver && sigLst[i].receiver === func)) {
                            idx = i;
                            break;
                        }
                    }
                    if (idx < 0) {
                        return this;
                    }
                    sigLst.splice(idx, 1);
                    if (!sigLst.length) {
                        delete sigCache[eventName];
                    }
                } 
                else if (sigLst === func || (sigLst.receiver && sigLst.receiver === func)) {
                    delete sigCache[eventName];
                }
            }
            return this;
        }, 
        signalOnce = function(eventName, func) {
            setSingleRV(true);
            var slf = this, 
            onit = function() {
                dropReceiver(eventName, onit);
                func.apply(slf, arguments);
            };
            onit.receiver = func;
            wen(eventName, onit);
            return this;
        }, 
        castSignal = function(eventName, args) {
            var recvrLst = receiverObjects(eventName), 
            k = {}, recvr = [], 
            i = 0, rspns = {};
            for (k in recvrLst) {
                if (recvrLst.hasOwnProperty(k)) {
                    i = recvrLst[k].length;
                    while (i--) {
                        recvr = recvrLst[k][i];
                        if (recvr.signalOnce === true) {
                            dropReceiver(eventName, recvr);
                        }
                        rspns = recvr.call(this, args || arguments || []);
                        if (rspns === getSingleRV()) {
                            dropReceiver(eventName, recvr);
                        }
                    }
                }
            }
            return this;
        };
        function isAry(obj) {
            return (obj.constructor === Array);
        }
        function receiverObjects(eventName) {
            var recvrLst = receivers(eventName), rspns;
            if (isAry(recvrLst)) {
                rspns = {};
                rspns[eventName] = recvrLst;
            }
            return rspns || recvrLst;
        }
        function receivers(eventName) {
            if (!sigCache) {
                sigCache = {};
            }
            if (!sigCache[eventName]) {
                sigCache[eventName] = [];
            }
            if (!isAry(sigCache[eventName])) {
                sigCache[eventName] = [sigCache[eventName]];
            }
            return sigCache[eventName];
        }
        function wen(eventName, func) {
            if (!sigCache) {
                sigCache = {};
            }
            if (!sigCache[eventName]) {
                sigCache[eventName] = func;
            } 
            else if (isAry(sigCache[eventName])) {
                sigCache[eventName].push(func);
            } 
            else {
                sigCache[eventName] = [sigCache[eventName], func];
            }
            return this;
        }
        return {
            signal: castSignal,
            receive: received,
            once: signalOnce,
            channels: receivers,
            drop: dropReceivers
        };
    }());
    
                                                                            

    public by sTiLL-iLL @ SniPitz-KND  4294  1  8  25

    Scribbles.js

    A non-blocking, thread-safe, async file-writer / appender for node.js.... oh yeah, its also faster than grease. Try iT!
    // scribbles.js
    
    var fs = require('fs'),
    	path = require('path'),
    	scribe = null,
    	canWrite = true,
    	roster = [],
    	scribblesQue = {};
    
    function Scribbles(file) {
      this.fPath = file;
      this.react = null;
    }
    
    scribe = Scribbles.prototype;
    scribe.scribble = function(data, reaction) {
    	var proceed = function () {
    		canWrite = true;
    		if (proceed) {
    			var dta = proceed;
    			proceed = null;
    			scribble(dta);
    		}
    	},
    	react = function(err, data, proceed) {
    		if (err) {
    			throw err;
    		}
    		proceed();
    	},
    	assign = function(reaction) {
    		this.react = reaction;
    		return this;
    	};
    	
    	if (!this.canWrite) {
    		proceed = data;
    		if (reaction) {
    			this.roster.push(reaction);
    		}
    		return this;
    	}
    	else {
    		var lazyfunc = null,
    			slf = this;
    		canWrite = false;
    		fs.appendFile(slf.fPath, data, function(err) {
    			proceed();
    			react(err, data, proceed); 
    			while (lazyfunc = roster.shift()) {
    				lazyfunc(err);
    			}
    			if (reaction){
    				reaction(err);
    			}
    		});
    	}
    	return this;
    };
    
    module.exports = function(fileName) {
      var fnm = path.resolve(fileName);
      return scribblesQue[fnm] = scribblesQue[fnm] || new Scribbles(fileName);
    }
    

    public by sTiLL-iLL  2168  1  8  31

    LineWorker.js swing shift yo!

    spin up a new web thread without a separate file.
    // lineWrker.js
    
    function workman() {
      setInterval(function() {
        postMessage({eat: "me"});
      }, 500);
    }
    
    var wkd = workman.toString();
    wkd = wkd.substring(wkd.indexOf("{")+1, wkd.lastIndexOf("}"));
    
    var blobbyJo = new Blob([wkd], { type: "application/javascript" });
    var wrkr = new Worker(URL.createObjectURL(blobbyJo));
    
    wrkr.onmessage = function(msgz) {
      console.log("msg", msgz);
    };            

    public by sTiLL-iLL @ SniPitz-KND  3708  0  8  22

    Lazy Loaded...... Lazy.js

    load your images on demand...
    // another lazy  image loader thang.....
    
    var lazy=(function() {
        this.load=function(elem, res) {
          if (document.querySelectorAll) {
              res=document.querySelectorAll(elem);
          } else {
            var dok=document, 
              sheet=dok.styleSheets[0] ||
              dok.createStyleSheet();
              sheet.addRule(elem,'foo:idx');
            for(var ln=dok.all,idx=0,lst=[],f=l.length;idx<foo;idx++) {
              (ln[isx].currentStyle.foo&&lst.push(ln[idx]));
            }
            sheet.removeRule(0);
            res=clst;
          }
          return res;
        }; 
        var receive=function(evt,func) {
          window.addEventListener?this.addEventListener(evt,func,false) :
            (window.attachEvent)?this.attachEvent('on'+evt,func):
            (this['on'+evt]=func);
        };
        var itHaz=function(k,object) {
          return Object.prototype.hasOwnProperty.call(k,object);
        };
        this.getLoaded=function(elem,func) {
          var img=new Image(),
          prnt=elem.parent;
          img.src=elem.getAttribute('data-src');
          img.addEventListener("load",function(evt) {
          if (!elem.parent) {
            prnt.replaceChild(img, elem)
          } else {
            elem.src=src;
          }
          (func)?func(): null;
        });
        img.src=src;
      };
      function inView(elem){
        var r=elem.getBoundingClientRect();
        return(r.top>=0&&r.left>=0&&
          r.top<=(window.innerHeight||
            document.documentElement.clientHeight)
          );
      }
      function cBak(pix, idx){
        return (pix.splice(idx,idx));
      }
      var pix=[],qry=layzee('img.lazy');
      this.doWork=function(){
        for (var idx=0;idx<images.length;idx++) {
          if (inView(pix[idx])){
            return getLoaded(pix[idx],cBak(pix,idx));
          }
        }
      };
      for (var idx=0;idx<qry.length;idx++) {
        pix.push(qry[idx]);
      }
      doWork();
      receive('scroll',dowork);
    }(this));                      

    public by sTiLL-iLL  2178  2  7  27

    Parallyzed.js.....never move again,.... or do....

    .... my pattern for concurrant, Parallel Xekution....sick asyncro stuff!
    // my pattern for executing a full-on parrallel series of async tasks!
    
    function Parallyzed(cBakLst, last) {
      var rzlts = [], cnt = 0;
      cBakLst.forEach(function(step, idx) {
        step(function() {
          rzlts[idx] = Array.prototype.slice.call(arguments);
          cnt++;
          if(cnt == cBakLst.length) {
            last(rzlts);
          }
        });
      });
    }
    
    var taskList = [];
    
    function myAsyncTask1(argz, step) {
      var compRZLT = Math.floor(Math.random() * 5 + 1) * 100;
      console.log('task with \''+argz+'\', return in '+compRZLT+' ms');
      setTimeout(function() {
        step(argz * 2);
      }, compRZLT);
    }
    
    taskList.push(myAsyncTask1);
    
    function myAsyncTask2(url, cBak) {
    	var xhr = new XMLHttpRequest();
    	xhr.open('GET', url, true);
    	xhr.responseType = 'JSON';
    	xhr.onload = function () {
    	if (this.status == 200) {
    			var lst = JSON.parse(xhr.responseText);
    			console.log("paths retreived... ");
    		}
    		cBak(lst);
    	};
    	xhr.send({});
    }
    
    taskList.push(myAsyncTask2);
    
    function myAsyncTask3(lst, xp, s, cBak) {
    	lst.forEach(function (itm) {
    		var mp = document.createElement('li');
    		mp.innerHTML = "<a href='#'>" + itm + "</a>";
    		mp.onclick = wenKlik;
    		xp.appendChild(mp);
    	});
    	s.appendChild(xp);
    	cBak(s);
    }
    
    taskList.push(myAsyncTask3);
    
    function myAsyncTask4(argz, step) {
      var compRZLT = Math.floor(Math.random() * 5 + 1) * 100;
      console.log('task with \''+argz+'\', return in '+compRZLT+' ms');
      setTimeout(function() {
        step(arg * 2);
      }, compRZLT);
    }
    
    taskList.push(myAsyncTask4);
    
    function myAsyncTask5(url, argz, step, cBak) {
    	var xhr = new XMLHttpRequest();
    	xhr.open('POST', url, true);
    	xhr.responseType = 'JSON';
    	xhr.onload = function () {
    	if (this.status == 200) {
    			var rzlt = JSON.parse(xhr.responseText);
    		}
    		step(cBak(rxlt));
    	};
    	xhr.send(argz);
    }
    
    taskList.push(myAsyncTask5);
    
    function lastOne(rzlts) {
      console.log('finished!', rzlts);
    }
    
    
    Parallyzed(taskList, lastOne);
    
                            
    • Public Snippets
    • Channels Snippets