Meteor code must always run within a Fiber

I would like to run an async function on the server. Calling run() in the following code works fine, however, the “Collection.insert” inside the final() throws the following Error:

Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.   

I tried multiple times using Meteor.wrapAsync, Meteor.bindEnvironment, and Async.wrap, but somehow cannot get rid of the error. Can somebody just give me a quick hint on what exactly I need to wrap in the following code? Thanks!

function asyncFct(arg, callback) {
    console.log('do something with \''+arg+'\', return 1 sec later');
    setTimeout(function() { 
        callback(arg); 
    }, 1000);  
}

var final = function(results) { 
    MyCollection.insert({"name": "Miri"}); 
    console.log('Done', results); 
}

run = function(){
    var results = [];
    var items = [1, 2, 3];
    items.forEach(function(item) {
        asyncFct(item, function(result){
            results.push(result);
            if(results.length == items.length) {
                final(results);
            }
        })
    });
}

use Meteor.setTimeout

1 Like

@arjunrajjain. Thanks that works for my particular example. How would I proceed if asynFct would be another asynchronous function such as reading/writing a file?

you are right! very good,thank you very much!