Functional State API

overview

Async Code


The following transform, runs one transform at a time, after that transform has returned, runs again if the underlying data has changed in the meantime.


let transforms = {
  task:async function(){ },
  result:function(){},
  $imports:()=>'data',
  promises:[],
  guid:0,
  $update:($val,that)=>{
    let data = $val(that.$imports());
    if(that.promise !== undefined) that.recent = true;
    else {
      that.promise = that.task();
      that.promise.then(function(result){
        that.result(result, that, $val);
        that.promise = undefined;
        if(that.recent === true){
          that.recent = false;
          that.$update($val, that)
        }
      });
    }
  }
};
				


This is encapsulated as the asyncOne function in the transforms module.


let ts = await import("/lib/functional-state/library/v1.0.0/transforms.mjs");

let transform = ts.asyncOne();
transform.$imports = ()=>'data';
transform.task = async function(){

};

transform.result = function(result, that, $val){

}
				


Async Code


The following code will execute every transform as the underlying data changes, even if there are currently running prior transformations running, but will ignore prior transformations if a later transformation returns first.


let transforms = {
  $imports:()=>'data',
  promises:[],
  guid:0,
  $update:($val, that)=>{
    let data = $val('data');
    that.guid += 1;
    let guid = that.guid;
    let promise = new Promise(function(resolve, reject){
      //... do something
      let test = { id:0 };
      while(that.promises.length >0 || test.id !== guid){
        test = that.promises.shift();
      }
      if(test.id === guid){
        //update whatever
      }
    });
    that.promises.push({
      id:guid,
      promise:promise
    });
  }
};

rd.render([button,label],{target:'content'});
				


The above example is coded in the transforms module. The following example demonstrates created a transform.


let ts = await import("/lib/functional-state/library/v1.0.0/transforms.mjs");

let transform = ts.asyncTruncated();
transform.$imports = ()=>'data';
transform.task = async function(){

};

transform.result = function(result, that, $val){

}
				


The user needs to provide a task function to execute the asynchronous task, and a result function that does something with the result.

Contents