0

I'm getting data from a promise that returns a string:

const connectedDevice = async () => {
   await BleClient.getConnectedDevices(optionalServices)
   .then(
      value => { return value[0].deviceId ) };
   )
   .catch(err => { console.log(err) });
}

and I've been calling the function connectedDevice() which reuslts in the string raturned by the promise being output to the console as expected.

However, if I try to use the promise string outside of the function itself, I was getting the promise itself being returned rather than the result of the promise. So, I modified my call to the function by adding await, like so:

const conn = await connectedDevice();

However conn is now just 'undefined' and I'm unsure of what I'm doing wrong.

How do I get the actual value of value[0].deviceId returned so that I can use the promise returned value outside of the connectedDevice() function?

Etheryte
  • 24,589
  • 11
  • 71
  • 116
Phill Healey
  • 3,084
  • 2
  • 33
  • 67
  • Is it intentional that you use `async` function without `await` inside? – Cerberus Jun 16 '22 at 10:37
  • you are neither returning anything from the `async () => {}` nor from the `.then()`, so it's not surprising, that you get `undefined`. – derpirscher Jun 16 '22 at 10:41
  • @derpirscher Sorry, I copied over the code I'd been messing around with. It's updated now. – Phill Healey Jun 16 '22 at 10:43
  • @Cerberus Its updated now. – Phill Healey Jun 16 '22 at 10:43
  • @PhillHealey still no `return` from `async () => { ... }` – derpirscher Jun 16 '22 at 10:43
  • @derpirscher Ok, so I'm clearly misunderstanding how I have to do this. I'm just going off what I'd read and I'm really just learning react. So, your pointer would be very welcome. – Phill Healey Jun 16 '22 at 10:45
  • @PhillHealey read the answers in the linked duplicate ... – derpirscher Jun 16 '22 at 10:46
  • @derpirscher I already went over that thread before posting. I'm just not seeing what I'm missing and how to fix it. Thanks for your time anyway. – Phill Healey Jun 16 '22 at 10:47
  • 1
    `async () => { ... }` is a function, that doesn't return anything. So of course if you `await` it, the result will be undefined ... You are `await` ing `BleClient.getConnectedDevices(...) ` but you are not doing anything with its result, especially you are not returing it ... The simplest would possibly be doing `return BleClient.getConnectedDevices( ...)` instead of `await BleClient.getConnectedDevices(...)` – derpirscher Jun 16 '22 at 10:49
  • @derpirscher Thank you! That works and I understand what's happening now. – Phill Healey Jun 16 '22 at 10:52

0 Answers0