2017-03-26 6 views
0

Je suis nouveau dans JS et asynchrone ... donc j'ai besoin d'aide :) Je dois retourner la valeur après la communication série. la lecture en série doit apparemment être fonction, donc je ne sais pas comment faire pour bloquer, ou en retourner une valeur ... le log console affiche la valeur, mais la valeur n'est pas retournée ... (probablement parce qu'elle est exécutée avant la série). aidez s'il vous plaît. Voici une partie de code:Comment retourner la valeur après une communication série NodeJS

var LightController = { 
getBrightness: function() { //get brightness 
    port.write(askcommand); 
    port.on('data', function (data) { 
     st = data.slice(-4, -3); 
     this.brightness = st.readInt8(0); 
     console.log(this.brightness) 
    }); 
    return this.brightness; 
    },  

lightAccessory 
     .getService(Service.Lightbulb) 
     .addCharacteristic(Characteristic.Brightness) 
     .on('get', function(callback) { 
     callback(null, LightController.getBrightness()); 
     }); 

Répondre

0
var LightController = { 
// add callback to get brightness function 
getBrightness: function(brightnessCallback) { //get brightness 
    port.write(askcommand); 
    port.on('data', function (data) { 
     st = data.slice(-4, -3); 
     this.brightness = st.readInt8(0); 
     console.log(this.brightness) 
     // call callback for get brightness function 
     brightnessCallback(this.brightness); 
    }); 
    return this.brightness; 
    } 
} 

lightAccessory 
     .getService(Service.Lightbulb) 
     .addCharacteristic(Characteristic.Brightness) 
     .on('get', function(callback) { 
      // call the get brightness function, passing anonymous function as brightness callback 
      LightController.getBrightness(function(brightness){ 
      // call original callback with brightness 
      callback(null, brightness); 
      }) 
     }); 
+0

MERCI !!! Ça marche!!! – MotoManiac