Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
Turning asynchronous function from a package to sync

This function goes through all the matrices of a keyboard, asks the keyboard for the keycode in each place and pushes it to the layerKeycodes array. The problem is that device.read() is asynchronous and I couldn't find a way to make it synchronous without having a super messy code. The problem is that the console.log() at the end (which will be return in production) gets fired before the keyboard replies and sends back the keycodes. I know that device.readSync() exists but the documentation of nodehid is bad, couldn't find how to use it.

const getLayerKeycodes = (keyboard, layer, rows, columns) => {
    //array that stores all the keycodes according to their order
    let layerKeycodes = [];
    //rows and columns start the count at 0 in low level, so we need to decrease one from the actual number. 
    columns --;
    rows --;
    //loop that asks about all the keycodes in a layer
    const dataReceived = (err, data) => {
        if(err) {
            return err;
        }
        // push the current keycode to the array
        // The keycode is always returned as the fifth object.
        layerKeycodes.push(data[5]);
        console.log(layerKeycodes);
    };  
    for (let r = 0 , c = 0;c <= columns; r ++){
        //callback to fire once data is receieved back from the keyboard.
        if(r > rows){
            c++;
            //r will turn to 0 once the continue fires and the loop executes again 
            r = -1;
            continue;
        }
        //Start listening and call dataReceived when data is received 
        keyboard[0].read(dataReceived);
        //Ask keyboard for information about keycode
        // [always 0 (first byte is ignored),always 0x04 (get_keycode),layer requested,row being checked,column being checked]
        keyboard[0].write([0x01,0x04,layer,r,c]);
    }
    console.log(layerKeycodes);
    
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!