'NodeJS & RaspberryPi - onoff ignoring setTimeout

I am setting up a small node server which can handle the switching on/off of some hard disks I've connected to my RaspberryPi. Now, I wrote a simple handler for the switching off, which should take care of 2 tasks:

  • unmounting the hard disk;
  • switch off the pin;

A non-elegant solution I've found so far, is to execute a command, wait for a certain amount of time, then switch off the hard disk:

const Gpio = require('onoff').Gpio;
const {exec} = require('child_process');
    handlers.switchOff = (data, callback) => {
        if (data.meta.destination != ''
            && data.pin != '') {
            let unmountCommand = "sudo -S umount -f -l " + data.meta.destination;
            let pinOut = new Gpio(data.pin, 'out');
            exec(unmountCommand, (error, stdout, stderr) => {
                    return '';
            });
            setTimeout(function(){
                pinOut.write(0);
                console.log('switched off');
            },10000);
            callback(200, { 'message': 'OK' });
        }
        callback(500, { 'message': 'SERVER ERROR' });
    };

But the behaviour of the setTimeout's filling is unexpected: it executes immediately the pinOut.write(0), while the console.log() is exectued after more or less 10 seconds. Any hint or leads about this behaviour? What am I missing here?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source