helloap
helloap

Reputation: 23

TypeError: Cannot read property 'then' of undefined for global variables

I am trying to check if bridgeObject.checkStatus has been called already with the isRunning global variable.

If it hasn't then I call it and set isRunning to true. Then when it's dont change is running back to false.

if (!this.isRunning){
  this.isRunning = true;
  bridgeObject.checkStatus().then(() => {
    this.isRunning = false;
  });
} else {
  console.log('Not allowed to checkstatus, Value isRunning= ' + this.isRunning); 
}

But I am getting this error:

TypeError: Cannot read property 'then' of undefined for global variables

I'm super new to programming so I haven't been able to figure out why I'm getting this error and what to do based on other answers here.

UPDATE:

Here is what checkStatus does

    checkStatus: function (mediaUrl) {
  console.log('bridge checkStatusOnDevice');
  if (typeof (Device) != 'undefined' && Device!= null) {
    Device.checkStatusOnDevice();
  }
  else
  {
    deviceStatusSuccess();
  }
},

Upvotes: 1

Views: 733

Answers (1)

pascalpuetz
pascalpuetz

Reputation: 5418

Your checkStatus function does not return anything - thus the result is undefined. You then try to call then on the result of your checkStatus function, which leads to your error message.

You need to make your checkStatus function return a promise if it is running asynchronously and you want to call then on the result.

This could look something like this:

checkStatus: function (mediaUrl) {
  return new Promise((resolve, reject) => {
     console.log('bridge checkStatusOnDevice');

     if (typeof (Device) != 'undefined' && Device!= null) {
       // call resolve/reject when the following call succeeded/failed respectively
       Device.checkStatusOnDevice();

       // This COULD be something like this, if the API is callback based:
       // Device.checkStatusOnDevice(() => resolve(), () => reject())
     } else {
       // call resolve/reject when the following call succeeded/failed respectively
       deviceStatusSuccess();
     }
  });
},

Upvotes: 1

Related Questions