View Single Post
  #1  
Old 08.12.2019, 19:01
noone1
Guest
 
Posts: n/a
Default [javascript] callAsync and named callback / lost in asynchronous space...

Hello,

I didn't find a way to use callback function in callAsync, so I ended up with something that seems overcomplicated. If somebody could give me an example to 're-sync' the standard output in the flow in this case.

Here I call a function that contains a callAsync and needs its result to go on, but in the context of this function I don't see variable accessible for a callback.

Meanwhile, here is my dirty, messy attempt:), while it is working I'm hopping something shorter:
I use an object.watch polyfill that switch a global param on variable change and use a while loop to check if the switch has been modified!

The problematic call from which I need a return inside the function's context is a simple test of echo %userprofile%.

I put functional script but it's part of a larger, so sorry for the mess;)

(At the beginning I just wanted to play a little with msdos hybrids to learn a bit of javascript but now I think I spent some time on SO and MDN and saw the evilness of javascript, lol.)


Spoiler:

Code:
'use strict';

disablePermissionChecks();
setDisableOnException(false);
setAdvancedAlert(true);

//------------------------------------------
// non native object.watch polyfill
//------------------------------------------
//Eli Grey initial version, improved Xose Lluis

if (!Object.prototype.watch) {

 Object.defineProperty(
   Object.prototype,
   "watch", {
     enumerable: false,
     configurable: true,
     writable: false,
     value: function (prop, handler) {
       var old = this[prop];
       var cur = old;
       //getsw=0;
       var getter = function () {return cur;};
       var setter = function (val) {
        old = cur;
        cur = handler.call(this,prop,old,val);
        //getsw=1;
        return cur;
       };
 
       // can't watch constants
       if (delete this[prop]) {
        Object.defineProperty(this,prop,{
            get: getter,
            set: setter,
            enumerable: true,
            configurable: true
        });
       }
    }
 });
}

//------------------------------------------
// settings
//------------------------------------------

const crlf="\r\n";
const sp=' ';
const bs=getEnvironment().pathSeparator;
const JD_TEMP=JD_HOME+bs+"tmp"+bs;

var start_date = new Date();
var today = start_date.toLocaleString();
var start_msg='-- start@'+today+crlf+crlf;

//obj to watch + switch
var getsw=0;
var geto = { mypath: '', username: '', usertemp: ''};

//act as var listener (trigger when modified)
geto.watch('mypath', function (id, oldval, newval) { 
    getsw=1;
    return newval;}
);

//----------- user defined ----------------- 

var mypath;                    //specify a path for tmp files or default will be used (desktop here)

if (typeof(mypath)=="undefined") {        //using it will define username and user temp folder for logfile
    getLocalPath();}            //will wait for async var to be set
                        
var log_file=mypath+'jsjd_log_tmp.txt';        // log file

var check_locpath='back to main:'+crlf+
'mypath:' +mypath+crlf+
'log_file:'+log_file;

del_file(log_file);
logf(start_msg+"working path: "+mypath+crlf,true);
logf(crlf+print_r(check_locpath));

alert('Hello '+geto.username+" \u0110");

//-- end -- //

//------------------------------------------
//getLocalPath
//------------------------------------------
//set mypath

function getLocalPath(){ 
//function(e,s,r) in callAsync is the callback function except it is an annonymous (unamed) function
//need to send standard output to a parser and then have the result sync here
//I didn't find how to use it so I make it call another function

    callAsync(function(e,s,r){coutput(e,s,r,"path");},"cmd","/c",'@echo off & echo.%userprofile%"');

    sync(); //wait till getsw switch is set

    //now we have the result (geto) from the console log parser  and we can go on
    
    /*choose default*/
    var default_path=geto.mypath+bs+"Desktop"+bs;
    //var default_path=default_path+"JDscripts"+bs;

    if (getPath(default_path)) {
        mypath=default_path;
    } else {
        mypath=JD_TEMP;
    }
}

//------------------------------------------
//sync
//------------------------------------------

function sync(dummy){//if watch switch used

    var i=0;
    while (this['getsw']!=1) {//global this
        if(i>3*Math.pow(10,6)) {break;}
    }
}

//------------------------------------------
//console log parser
//------------------------------------------

function coutput(e,s,r,typ){

    //split console log 
    var b=s.split(crlf);

    /*output for local path*/
    if (typ=="path"){

        // mypath=b[0]=%userprofile%
        geto.mypath=b[0].trim();
        geto.username=b[0].split(bs).pop();
        geto.usertemp=getEnv('TEMP');
    }
}

//------------------------------------------
//format&output
//------------------------------------------

function file_exist(myfile) {
    return getPath(myfile).exists();
}

function del_file(myfile){ //non recursive
    if (file_exist(myfile)) deleteFile(myfile,false);
}

function logf(log_content,bAppend){
//call a 1st time with true to create the file, then bAppend is obsolete

	if (typeof bAppend === 'undefined') bAppend = true;
	if (!bAppend) {
		del_file(log_file);
	} else {
		if (typeof log_file!=="undefined") {
			writeFile(log_file,log_content,bAppend);
		}else{
			alert(' /!\\ attempt to log to undefined file /!\\'
		}
	}
}

function print_r(arr, level) {
//stackoverflow.com/a/9613740

    var dumped_text = "";
    if (!level) level = 0;

    var level_padding = "";//The padding given at the beginning of the line.
    for (var j = 0; j < level + 1; j++) level_padding += "    ";

    if (typeof(arr) == 'object') { 
        for (var item in arr) {
            var value = arr[item];

            if (typeof(value) == 'object') { 
                dumped_text += level_padding + item + " ...\n";
                dumped_text += print_r(value, level + 1);
            } else {
                dumped_text += level_padding + item + " => " + value + "\n";
            }
        }
    } else { 
        dumped_text = "=> " + arr + " <=(" + typeof(arr) + ")";
    }
    return dumped_text;
}

Last edited by noone1; 08.12.2019 at 21:43.
Reply With Quote