-5

I have 2 variables. One is assigned inside a .then and the other assigned in a function. Later on only 1 is defined.

Code excerpt...

let user;
let station;
const app = express();

app.post("/api/user", (req, res) => {
    user = req.body.user; // Breakpoint added here to confirm user set
}

// Uses serialport module. Called when data received on serial port
function serialPortListener(data) {
    getStation(data) // Retrieves record from database
    .then(s => {
        station = s; // Breakpoint added here to confirm station set
    ...
}

I set breakpoints on both methods to confirm the variables are set. When I try to access them, later on, only user is defined. I'm assuming it's something to do with the context in which station is set?

station is not assigned anywhere else.

TedTrippin
  • 3,525
  • 5
  • 28
  • 46
  • please put `getStation` function also.It seems that function is not returning value, therefore it is giving undefined. – mabc224 Jan 30 '20 at 13:53
  • 1
    is the promise getStation() resolved? Did you check if the line station = s was called? – Akora Jan 30 '20 at 13:53
  • "I set breakpoints..." including on `station = s` to confirm it was set – TedTrippin Jan 30 '20 at 13:54
  • I had the same problem just yesterday; it's because return/ variable set from inside an asynchronous function does not work... [This YouTube video](https://www.youtube.com/watch?v=lnBimoVllfo&t=73s) helped me to understand it, look at his syntax and try to implement it in your application. – TKret96 Jan 30 '20 at 14:04
  • I think someone is using something synchronously when it is asynchronous. AKA You order a pizza and as soon as you order you try to eat it. Not going to happen. – epascarello Jan 30 '20 at 19:06

1 Answers1

-5

I believe the problem is due to the way var and let works. Try changing let with var, it should work. For the differences between var and let read this.

Edit: Ran the code here is a working code.

let user;
let station = 'ABC';

let getStation = new Promise(function (resolve, reject) {
    setTimeout(() => resolve('XYZ'), 1000);
});

// Uses serialport module. Called when data received on serial port
function serialPortListener(data) {
    getStation
    .then((s) => {
        console.log(station); // station is available with value ABC
        station = s;
        console.log(station); // station has value changed to XYZ
    });
}

console.log(serialPortListener('data'));

The problem in your codes is in the line

 getStation(data)
  • No that's not the reason here – TKret96 Jan 30 '20 at 14:00
  • can you provide a fiddle? – Ranjeet Kumar Jan 30 '20 at 14:05
  • `let station = serialPortListener(xxx).then(s => return s);` ```function serialPortListener(data) { return getStation(data) } ``` I think it should be something similar to this but I'm still at the beginning of understanding asynchronous functions. Have a look at [this video](https://www.youtube.com/watch?v=lnBimoVllfo). – TKret96 Jan 30 '20 at 14:10