Start using async/await instead of promises and callbacks

Using await makes chaining Promises almost as simple as using sync-style coding on the server. In principle I would take something like that callWithPromise and just use multiple calls:

const thing = await callWithPromise('methodA'), {} );
const factor = await callWithPromise('methodB', { item: thing } );
const result = await callWithPromise('methodC', { item: thing, factor } );

The only “gotchas” you need to be aware of are:

  1. You can only await inside an async function. However, you can do funky things like Template.bob.onCreated(async function() {... which makes your entire onCreated async.
  2. There is still likely to be a resolution step if you want to get a result from an await chain out of your async function and back into your “normal” code. In Meteor you can do this easily by making use of ReactiveVars.

So, in Blaze, you could do something like:

Template.bob.onCreated(async function() {
  this.result = new ReactiveVar();
  const thing = await callWithPromise('methodA'), {} );
  const factor = await callWithPromise('methodB', { item: thing } );
  this.result.set(await callWithPromise('methodC', { item: thing, factor } ));
}

Template.bob.helpers({
  getResult() {
    return Template.instance().result.get();
  }
});
5 Likes