Search code examples
asynchronousmeteorfibersnode-fibers

How to use wrapAsync in Meteor


I am having trouble figuring out how to use wrapAsync properly using Meteor. I am currently working with node-apac and the Amazon Product Advertising API.

If am trying to run the following code, how do I run it asynchronously:

opHelper.execute('ItemSearch', {
    'SearchIndex': 'Books',
    'Keywords': 'harry potter',
    'ResponseGroup': 'ItemAttributes, Offers'
}, function(err, results) {
    console.log(results);
});

I have tried to watch several videos, but am having trouble


Solution

  • Meteor.wrapAsync takes an asynchronous method like opHelper.execute and makes it synchronous. It can do this so long as the last param taken by the method returns a callback where the first param is the error and second the result. This is just like your method!

    You make a new method that is synchronous:

    var opExecuteSynchronous = Meteor.wrapAsync(opHelper.Execute, opHelper);
    

    The first param opHelper.Execute is the method you want to make asynchronous, and the second param is the context of the method (opHelper).

    You can use this synchronously now:

    var results = opExecuteSynchronous('ItemSearch', {
        'SearchIndex': 'Books',
        'Keywords': 'harry potter',
        'ResponseGroup': 'ItemAttributes, Offers'
    })
    

    This will throw an error if err is called instead of results in the callback.