Skip to content

Promises instead of callbacks #411

Description

@MoritzCooks

I implemented react-native-health and react-native-health-connect. I try to get these packages together in one lib file. What bothers me the most, is that react-native-health is taking callbacks instead of simply returning promises.
Is there any reason not to return a promise?

With the current approach you either need an additional state variable that reflects the isAvailable state or you wrap the function in a promise. My current implementation of checking if the HealthKit is available looks somewhat like this:

const isAvailable = await new Promise(resolve => {
  AppleHealthKit.isAvailable((err, available) => {
    if (err) Sentry.captureException(err)

    return resolve(available)
  })
}

I have to wrap a promise around it, to be able to await the resolved value. I could get rid of this promise wrapper if the isAvailable method would simply return a promise instead. Also it would look a lot cleaner not only because of less nesting:

try {
  return await AppleHealthKit.isAvailable()
} catch (error) {
  Sentry.captureException(error)
}
return false

I saw this in a couple methods of this package that the result gets returned with a callback. This pattern is quite uncommon in my opinion. And as I already pointed out it needs additional wrappers to actually await the response.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions