Meteor is mostly backward compatible to even < 1.0 projects. Therefore lots of code is still callback based. So is theMeteor.call
method. You can easily wrap it into a Promise-based approach:
exportconstcallMethod=({name,args})=>newPromise((resolve,reject)=>{Meteor.call(name,args,(error,result)=>{if(error){returnreject(error)}returnresolve(result)})})
AlthoughMeteor.call
supports multiple arguments I rather prefer to pass a single object with named arguments to keep the code more expressive.
You can then usecallMethod
natively in an async environment:
Template.myTemplate.events({'click .some-button':asyncfunction(event,templateInstance){constage=awaitcallMethod({name:'getAge',args:{name:'John Doe'}})console.log(age)// whatever the method returned}})
Additionally you can "hook" into these calls and thus mix callbacks with promises and create a decent UX experience when method calls are part of user interactions:
exportconstcallMethod=({name,args,prepare,receive,success,failure})=>{// before callif(typeofprepare==='function'){prepare()}// create the promiseconstpromise=newPromise((resolve,reject)=>{Meteor.call(name,args,(error,result)=>{// on receivedif(typeofreceive==='function'){receive()}if(error){returnreject(error)}returnresolve(result)})})// on successif(typeofsuccess==='function'){promise.then(success)}// on errorif(typeoffailure==='function'){promise.catch(failure)}returnpromise}
The code can then be used for example to display a "waiting" indicator:
Template.myTemplate.events({'click .update-button':asyncfunction(event,templateInstance){constupdatedDoc=awaitcallMethod({name:'updateUser',args:{name:'John Doe',age:42},prepare:()=>templateInstance.state.set('updating',true),receive:()=>templateInstance.state.set('updating',false),failure:er=>alert(er),success:()=>alert('updated')})// process updatedDoc if desired})
I regularly publish articles here on dev.to aboutMeteor andJavaScript. If you like what you are reading and want to support me, you cansend me a tip via PayPal.
You can also find (and contact) me onGitHub,Twitter andLinkedIn.
Keep up with the latest development on Meteor by visitingtheir blog and if you are the same into Meteor like I am and want to show it to the world, you should check out theMeteor merch store.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse