Home > Blockchain >  How to "wait" for a property that get its value from a callback function?
How to "wait" for a property that get its value from a callback function?

Time:11-22

Here is my code in TypeScript:

private getInfoSystem = () => {
    this.systemInfo  = {
        cpuSpeed: 0 ,
        totalRam: os.totalmem(),
        freeRam: os.freemem(),
        sysUpTime: os_utils.sysUptime(),
        loadAvgMinutes: {
            one: os_utils.loadavg(1),
            five: os_utils.loadavg(5),
            fifteen: os_utils.loadavg(15),
            }
    }
    
    si.cpuCurrentSpeed().then ((data)=> {
        this.systemInfo.cpuSpeed = data.avg ;
    });
    return this.systemInfo;
};

The property "cpuSpeed" first initialized to Zero and then I call the method cpuCurrentSpeed() which use a callback function and I try to put the value in "cpuSpeed". The problem is that the the data of cpuCurrentSpeed() is late and the return value not include the wanted value in "cpuSpeed".

CodePudding user response:

Because you are using .then on the cpuCurrentSpeed call, I assume that it's returning a Promise and not using callbacks. If it's like this, you could make your method asynchronous and await it:

private getInfoSystem = async () => {
     this.systemInfo  = {
        cpuSpeed: 0 ,
        totalRam: os.totalmem(),
        freeRam: os.freemem(),
        sysUpTime: os_utils.sysUptime(),
        loadAvgMinutes: {
            one: os_utils.loadavg(1),
            five: os_utils.loadavg(5),
            fifteen: os_utils.loadavg(15),
        }
    }
    this.systemInfo.cpuSpeed = (await si.cpuCurrentSpeed()).avg;
    return this.systemInfo;

};

Please note, that in this case your method also returns a Promise of the type of the value of this.systemInfo afterwards (which then needs to be awaited again by the calling method).

Otherwise, you can only rely on the returning value of Promises or callbacks inside of the callback because of it's asynchronous nature.

  • Related