Validated method and async/await, then/catch


#1

Hi,
Is it possible to use then/catch on a validated method from the client, instead of callbacks?
For example, on the server

export async function zonesselect(systemId, geometry) {
  const selectedZones = await Zones.find({ systemId, geometry }).fetch();
  const selectedZoneIds = selectedZones.map(zone => (zone._id));
  return selectedZoneIds;
}

Shared between client and server

export const zonesSelect = new ValidatedMethod({
  name: 'zones.Select',
  validate: new SimpleSchema({
    systemId: { type: String, regEx: SimpleSchema.RegEx.Id },
    geometry: { type: Object, blackbox: true },
  }).validator(),
  run({ systemId, geometry }) {
    if (Meteor.isServer) {
      import { iseditorismanager } from '../server/user';
      import { zonesselect } from '../../collections/server/Zones';
      if (iseditorismanager(systemId)) {
        return zonesselect(systemId, geometry);
      } else throw new Meteor.Error('permission denied', 'User not a system manager or editor');
    }
  },
});

On the client something like…

        zonesSelect.call({ systemId, geometry })
          .then((zoneIds) => {
            zoneIds.forEach((zoneId) => {
              console.log('zoneId', zoneId);
            });
          })
          .catch((err) => { console.log('error', err); });

#2

You will probably want to use this mixin: https://github.com/didericis/callpromise-mixin/

Then you can do:

try {
  const zoneIds = await zonesSelect.callPromise({ systemId, geometry });
} catch (err) {
  console.log(err);
}

#3

Thank you for the solution. Can this only be done with mixins, or is there a more future proof alternative? I heard somewhere that mixins are on their way out.


#4

If you’re referring to something like this, then mixins are only on their way out in terms of React and their mixin support.

In regards to this package, it was built to support mixins, so there’s no reason to believe they wouldn’t be supported moving forward. This package is pretty stable – I’d be surprised to see many changes at all, as it’s mostly a logical wrapper around some best practices when it comes to methods.