How to make method synchronous in Meteor using Future
Posted By : Parveen Kumar Yadav | 27-Dec-2016
Sometime we need that our method ru in synchronous manner not asynchronous in Meteor. There are few way by which you can achieve synchronous manner of functions. One of the way is use of Fiber/Future.For example we are doing some other method call or DB query which are generally asynchronous. So our function return undefined without waiting the result of query and other method result, but we want that our function must wait for the result and until and unless the result not come our function will not return the value. SO we can do something like this:-
Meteor.methods({ test: function(FKmarketAccObj, userObj) { var result var requestBodyHeaderObj = Meteor.call('getRequestBodyAndHeaderForAPI) if(requestBodyHeaderObj){ result = Meteor.call('getSearchOrdersAPI', requestBodyHeaderObj, userObj); } return result }, })
In above example it will return undefined without waiting the response of getSearchOrdersAPI method but we want result must not be send to client until and unless there is some value in result variable. So use the future:-
Meteor.methods({ test: function(FKmarketAccObj, userObj) { var fut = new Future(),result; var requestBodyHeaderObj = Meteor.call('getRequestBodyAndHeaderForAPI) if(requestBodyHeaderObj){ result = Meteor.call('getSearchOrdersAPI', requestBodyHeaderObj, userObj); } fut['return'](result); return fut.wait(); }, })
In above example you need follow these steps:-
1)Add the module of future 1)create an instance of future via var fut = new Future(); 2)Add return fut.wait() as the last line before method end so it will wait for response 3)Return the result directly to client side or method from where it called via fut['return](result)
Hope it will help Thanks!
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Parveen Kumar Yadav
Parveen is an experienced Java Developer working on Java, J2EE, Spring, Hibernate, Grails ,Node.js,Meteor,Blaze, Neo4j, MongoDB, Wowza Streaming Server,FFMPEG,Video transcoding,Amazon web services, AngularJs, javascript. He likes to learn new technologies