Meteor wrapAsync or bindEnvironment without standard callback signature

前端 未结 1 1756
再見小時候
再見小時候 2021-01-23 14:24

I\'m trying to call createTableIfNotExists in this npm package, and do so synchronously in Meteor, server-side. https://www.npmjs.com/package/azure-storage

相关标签:
1条回答
  • 2021-01-23 14:55

    You can use the Future from the fibers/future (node-fibers) package, which is just a different abstraction layer of fibers as this async/await implementation or this promise implementation are, too. (Note, that using a fiber directly is not recommended).

    Generic Future pattern

    As you already pointed out, you can solve this issue also using async/await or using promises.

    However, if you want to know how to use a Future instance, you can follow this popular pattern, which I make use of in many of my applications.

    Future pattern with Meteor.bindEnvironment

    Including the bindEnvironment into this pattern, and restructuring the code a bit, it looks like the following:

    import Future from 'fibers/future';
    
    Meteor.methods({
        myMeteorMethod: function() {
            // load Future
            const myFuture = new Future();
    
            // create bound callback, that uses the future
            const boundCallback = Meteor.bindEnvironment(function (error,results){
                if(error){
                  myFuture.throw(error);
                }else{
                  myFuture.return(results);
                }
            });
    
            // call the function and pass bound callback
            SomeAsynchronousFunction("foo", boundCallback);
    
            return myFuture.wait();
        }
    });
    

    Applied to code example

    Applying this modification of the pattern to your code, it could result in something like the code below. Note, that I separated the callback from being created inside the function simply because of readability. You can of course just create it inside the function head, as you typically do.

    import Future from 'fibers/future';
    
    var demoFunction = function(){
        // load Future
        const myFuture = new Future();
    
        // create bound callback, that uses the future
        const boundCallback = Meteor.bindEnvironment(function (error, result, response) {
            if (error) {
                myFuture.throw(new Meteor.Error(500, "table create error - " + asTableName + ": "+ error));
            }
    
            // do whatever you need to do here
            // with result and response...
    
            if (result) {
                myFuture.return(result);
            }                   
        });
    
        var tableService = azure.createTableService(acctName, acctKey);
    
        // pass the bound callback here
        tableService.createTableIfNotExists(asTableName, boundCallback);
    
        return myFuture.wait();
    
    }
    
    0 讨论(0)
提交回复
热议问题