0

I'm making an HTTP request to an API and would like to save the response body into a MongoDB Collection.

But because node is asynchronous I can't find a way to reference my data outside the callbacks, and Meteor does not allow saving into a collection outside the main fiber.

I've tried event emitters but they are still outside the fiber, also attempted to use Meteor.wrapAsync, but have not been able to structure it right.

Thanks!

var api_data;

function getData(url, callback) {

  request(url, callback);

};


function parseData(error, response, body)

{

    var localData = JSON.parse(body);

    api_data = localData; <-- How to get this outside the callback.


};


getData(api_url_full, parseData);
Kirill Sajaev
  • 143
  • 1
  • 8
  • Thanks for reference, I'm looking through it but struggling to understand, since I'm also using callbacks in my own functions. – Kirill Sajaev Dec 18 '16 at 12:29
  • i guess i can't post an answer because it's been marked as a duplicate. what you need are Futures. the problem you're facing is that your function has exited before your data came back. – zim Dec 18 '16 at 19:02
  • Futures can solve that. you need to import futures (let Future = Npm.require('fibers/future');) and define one at the top of your function (let future = new Future();). Then at the end of your function, return the wait on that future (return future.wait();). now your function won't return until that future is resolved. you can do so successfully, i.e. after your data comes back and you save it (future.return(data); or just future.return()), or if you encounter an error you can indicate so with a throw (future.throw(new Meteor.Error('500', "oops"));). Good luck. – zim Dec 18 '16 at 19:02
  • ah awesome thank you, that worked like a charm. Much easier implementation than wrapAsync I think. – Kirill Sajaev Dec 18 '16 at 21:39

0 Answers0