.then is not a function

This is a part of a code that reads Bluetooth LE data. Upon connecting the device, I expected it to display the data, instead I got error “bluetoothDevice.then is not a function”.

function onScanButtonClick() {
  let options = {filters: []};

  
    options.filters.push({services: ['battery_service', 'device_information']});

  bluetoothDevice = null;
  console.log('Requesting Bluetooth Device...');
  navigator.bluetooth.requestDevice(options)
  .then(device => {
    bluetoothDevice = device;
    bluetoothDevice.addEventListener('gattserverdisconnected', onDisconnected);
    return connect();
  })
  .catch(error => {
    console.log('Argh! ' + error);
  });
}

function connect() {
  console.log('Connecting to Bluetooth Device...');
  return bluetoothDevice.gatt.connect()
  .then(server => {
    console.log('> Bluetooth Device connected');
    getBatteryPercent();
    getFW();
    getHW();
    getMACAddr();
    getMFGName();
    getModelNum();
  });
}

How can I fix this error?

Hi @chenphilip14, there is no attempted bluetoothDevice.then() call in the code you posted… but my guess would be that bluetoothDevice is still null then. Anyway the error message should also give you a line number, could you post that code as well?

1 Like

The error is called from this line:

console.log('Argh! ' + error);

and the line in problem is here:

  .then(device => {
    bluetoothDevice = device;
    bluetoothDevice.addEventListener('gattserverdisconnected', onDisconnected);
    return connect();
  })

Hm again there’s no call to bluetoothDevice.then() here… the error message should also give you a stack trace though where the error was actually thrown, maybe in one of the functions you’re calling inside connect()?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.