[SOLVED] Promise.await in non-meteor apps

Hi there,

I have a meteor app which has a rather large class to interact with an external API. It has an axios instance, but I created a request method for the class which calls axios using Meteor’s Promise.await. Because of this, every method of the class is defined as a synchronous function. E.g.:

getReservations() {
  // this.request returns Promise.await(...)
  return this.request({ url: '/v2/reservations', method: 'get' })
}

Now my problem is that if I want to use this class in a non-meteor app (I’d like to create some lightweight workers to offload some cronjobs of the main meteor app), I’d have to convert every method which uses this wrapped request method to an async method. So my question is, is there a way to use Promise.await in a non-meteor app? Or if it’s not possible and I decide to re-write the class to use async methods, how can I call Meteor.wrapAsync to “convert” an entire class (with a lot of async methods) to be synchronous?

You can get those methods from the meteor-promise package on npm:

Meteor uses and maintains this package directly, so it’s always up to date with Meteor.

Note that you’ll need to follow the Readme instructions on adding Fibers support and then replace the system promise with this polyfill

2 Likes

btw if it’s just to set in a cron a more easy way should be to use one of the numerous cron packages available like https://atmospherejs.com/mrt/cron

Thinking about this a bit more, you could probably use a proxy to automatically Promise.await every method:

import { externalAPIModule } from 'external-api-module';

const meteorizedModule  = new Proxy(externalAPIModule, {
  get(obj, prop) {
    const value = Reflect.get(obj, prop);
    if (typeof value === function) {
      return function(...args) { return Promise.await(value.apply(obj, args)); }
    }
    return value
  }
});

export { meteorizedModule as externalAPIModule }

This means every time you access a function on the class, it should automatically wrap it with Promise.await

Which would make using the original class much easier to share, since Fibers are unusual to a lot of people

1 Like