ASYNCRESULT

DBJ AsyncResult API

HTML

<button onclick="test_async_result()">London was small too</button><hr/>

JavaScript

// AsynResult V 8.0
// MIT style (c) 2009-2015 by DBJ.ORG
// caling example
// spawn({ 'worker': w1, 'delay': 1000, 'callback': on_async_finished }, 1, 2, 3)
//
// Mandatory arguments :
// 1:single JSON object where
// worker   [mandatory] function pointer of the worker to execute asynchronously
// delay    [optional]  delayed execution time unit in microseconds, if null then 1.
// callback [optional]  called 'back' when worker is done with AsyncResult instance
//                      as its only argument
// [optional]
// any arguments required by a worker function
//
function spawn ( ){
var AsyncResult = function(args_) {
var FP = args_[0].worker;
var tu = parseInt(args_[0].tu === null ? 1 : args_[0].tu);
tu = (tu > spawn.maxdelay ? spawn.maxdelay : tu)
var CB = args_[0].callback;
// create properties on the curent instance
 this.done = false;
 this.retval = null;
 this.tid = null;
 this.callback = CB;
 // preserve the current instance aka 'this' in 'that'
var that = this;
// transform arguments to array and cut the first element
// thus leaving arguments for FP
that.args = Array.prototype.slice.call(args_).slice(1);
// be 'future proof'
// http://wiki.ecmascript.org/doku.php?id=proposals:json_encoding_and_decoding&s=tojsonstring
// and use: http://www.json.org/json2.js
this.toJSONString = function() { return JSON.stringify(that); }
this.toString = function() {
// return JSON formated object exposing private properties
// NOTE: this idiom exposes private properties without get/set methods
 return this.toJSONString();        }
// this private method is delay executed *outside* of the context of the current instance
// it is executed in the context of the 'global space' aka the 'window' object
function doit(x) {
     try {
 // execute FP(args), and preserve its return value
 // use 'that' for execution contest
 that.retval = FP.apply(that, that.args);
 // signal that execution finished ok
 that.done = true;
 } catch (x) {
 // FP() caused an exception
 that.retval...