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!

About Author

Author Image
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

Request for Proposal

Name is required

Comment is required

Sending message..