Last active
November 1, 2018 17:33
-
-
Save andrewlorenz/8f8420f7d0645a2254609b6bce14b63c to your computer and use it in GitHub Desktop.
Meteor methods calling async server code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Meteor methods are a means by which a client can execute synchronous code on the server as if it was local, and wait for the result before continuing. | |
The important word to note here is "synchronous" - meteor methods are only good "out of the box" if the server-side code it is executing is non-blocking. So what do we do when we need to execute asynchronous code on the server? | |
There are 3 possible approaches: | |
a) Meteor.wrapAsync | |
b) async/await | |
c) fibers/future | |
for all 3, the client call is identical in all 3 cases: | |
import { Meteor } from 'meteor/meteor'; | |
Meteor.call('myAsyncMethod', (err, response) => { | |
if (err) { | |
... handle error | |
return false; | |
} | |
... process response data | |
}); | |
a) Meteor.wrapAsync | |
import { Meteor } from 'meteor/meteor'; | |
Meteor.methods({ | |
myAsyncMethod() { | |
const asyncFunc = Meteor.wrapAsync(aCallToSomethingThatRunsAsync); | |
const something = asyncFunc(); | |
... do other stuff | |
return something; | |
}, | |
}); | |
b) async/await | |
import { Meteor } from 'meteor/meteor'; | |
Meteor.methods({ | |
async myAsyncMethod() { | |
const something = await aCallToSomethingThatRunsAsync(); | |
... do other stuff | |
return something; | |
}, | |
}); | |
c) fibers/future | |
import Future from 'fibers/future'; | |
const future = new Future(); | |
aCallToSomethingThatRunsAsync((err, something) => { | |
future.return(something); | |
}); | |
return future.wait(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment