0

My goal is to get the data from a method. The method return a Promise<BluetoothDevice[]>.

I would like to create a 2nd method to invoke the 1st method. The 2nd method should not return a Promise, instead it should return the data immediately.

This is the interface

interface BluetoothModule {
  getBondedDevices(): Promise<BluetoothDevice[]>;
}

This is how I plan to use it.

const App = () => {
  const bluetoothList = BluetoothModule.getBondedDevices();

  console.log(bluetoothList);

  return <Text>Hello, this is what the user see.</Text>
}

What I've tried

  1. Create a global method.
const getBondedDevices = async () => await BluetoothModule.getBondedDevices(); // This returns Promise<BluetoothDevice[]>
  1. Create a global method
const getBondedDevices = BluetoothModule.getBondedDevices();

const App = () => {
  const bluetoothList = getBondedDevices; // this returns the list, somehow... I find it weird. I will post the log below.
  const bluetoothList2 = BluetoothModule.getBondedDevices(); // this does not return the list.

  console.log(bluetoothList);
  console.log(bluetoothList2);

  return <Text>This is what the user see</TexT>
}

This is the log for the 2nd method

{"_U": 0, "_V": 1, "_W": [{"address": "00:13:04:84:03:07", "isConnected": false, "name": "BTHP1"}, {"address": "00:13:04:84:03:6F", "isConnected": false, "name": "BTHP1"}], "_X": null}
{"_U": 0, "_V": 0, "_W": null, "_X": null}
Jason Rich Darmawan
  • 1,607
  • 3
  • 14
  • 31
  • 2
    *"The method return a `Promise`. I would like to create a 2nd method to invoke the 1st method. The 2nd method should not return a Promise, instead it should return the data immediately."* I'm afraid that's just not possible. You can't get the result of an asynchronous operation synchronously. It's just not possible. – T.J. Crowder Feb 13 '21 at 15:26
  • What you can do instead is add a state item that you fill in from a `useEffect` callback: https://pastebin.com/tVMyDyxd If your environment/bundler supports [top-level `await`](https://github.com/tc39/proposal-top-level-await), you could delay your first render until you get the list by loading the list with a top-level `await` of `getBondedDevices`, but it's not a good UX to delay your first render like that. – T.J. Crowder Feb 13 '21 at 15:31
  • 1
    @T.J.Crowder Thank you for bringing top-level await to my attention. think what I need is a global splash screen and the top-level await. In the mean time, I will use a scoped splash screen and useEffect for better readability. – Jason Rich Darmawan Feb 13 '21 at 15:37

0 Answers0