1

I have a bunch of code in express which needs to be run synchronously. To achieve this I am using fibers/future library. The code is working properly but I am not confident that if it is the best way to achieve sync code from fibers/future.

CODE

  • Functions

    var api_object = Future.wrap(function(arg1, callback){
    
            var obj = new API(arg1.config.consumer_key,
                              arg1.config.consumer_secret);
    
            return callback(null, obj);  });
    

var create_customer = Future.wrap(function(api_object, name, callback){

api_object.create_customer_app(
    {"name": name
    }, function(err,api_respone){



   return callback(null, api_response);
    });     });
  • API

router.route('/create_customer').post(function(req, res){

var arg1 = req.body.arg;
 var customer_name = req.body.customer_name;

 Future.task(function(){
      var api_object = func.api_obejct(arg1).wait();
      var customer_create = func.create_customer(api_object, name).wait();   }).detach();   });

Here as you can see I am using fibers/future to make my async calls work in sync manner. I am using .wait() to wait for the command to complete and binding the tasks and functions in future. Is this approach correct?

Nikhil Parmar
  • 876
  • 2
  • 11
  • 27
  • Why does it need to run synchronously? – robertklep Jun 09 '16 at 09:45
  • It needs to run in sync because it is generating api_object from different functions and then passing that to other function to run the API endpoint. Moreover in between there are more tasks – Nikhil Parmar Jun 09 '16 at 12:12
  • So what you're actually looking for is something to help manage a lot of async calls? – robertklep Jun 09 '16 at 12:14
  • @robertklep yes yes actually of all the libraries I found this easy to implement and now just want to know if it is the best technique of all – Nikhil Parmar Jun 10 '16 at 02:49
  • Node is all about asynchronous code, so I think it's worthwhile to embrace that fact and learn how to work with it. How exactly depends a lot on preference, there's the great [`async`](https://github.com/caolan/async) library, there are promises, and especially combined with the latter, [`co`](https://www.npmjs.com/package/co) _almost_ makes your code look like it's synchronous (even if it's not). – robertklep Jun 10 '16 at 07:27
  • @robertklep to embrace the fact that node is asynchronous I can not make a callback hell in my code. `async` library is good. But currently I am using `fibers` question is about it. Anyways thanks ! – Nikhil Parmar Jun 10 '16 at 13:18

0 Answers0