Saturday 21 July 2018

Get value from server in client

I'm trying to return a single string from my server in Electron/nodejs and having some trouble.

I have a function called handleHWCompare, which has a type and value sent to it. With certain types, I need to send the value to the server which will process and return a slightly altered string to match some specific cases in my script.

The problem is, I can't figure out how to properly use the returned data in the function.

This function has multiple types of returns, because it's used for multiple purposes. Here is my function:

function handleHWCompare(type, server, client, doActions = true) {

        difference = leven(server, client);

        if(difference <= 2) {
            if(doActions) {
                //do some actions
            }
            return true;
        } else {
            if(doActions) {
                //do some actions
            }
            return false;
        }

    }

I've tried a few things for this.

At the top of the function, I tried this:

if(type == "mobo" || type == "sku") {
            https.get('https://example.com/api/check_rules.php?type=' + type + '&value='+ client, (res) => {
                res.setEncoding('utf8');
                res.on('data', function (result) {
                    console.log('altered: ' + result);
                    client = result;
                });
            });
            console.log('variable: ' + client);
        }

And I understand this is a problem because if sync/async, but it doesn't actually set the value in time to use it, it stays as the old one for the function.

I tried putting all the existing code from the function inside the res.on part of https.get, but that didn't work because it broke the return true and return false.

I tried using a callback function which almost worked but I couldn't figure out how to make the existing return true and return false parts to work, so it broke my script (I don't have the code for this anymore as I've been trying things for hours).

It seems so difficult to do such a simple thing, I don't want to rewrite my entire app structure just for this. How can I send this value and retrieve an altered version in my client inside this function?

I'm aware of things like await and promises, but no matter how hard I try I can't grasp the concept on how to use them.



from Get value from server in client

No comments:

Post a Comment