I think you’re perhaps misunderstanding some of the core concepts of Meteor and its use of Fibers for sync-style programming.
It may be helpful to just go over some of the fundamentals.
On the server, Meteor code uses Fibers to achieve sync-style programming, in which callbacks are not used. However, Fibers are an example of coroutines, and have nothing to do do with Promises and async/await
syntax. Meteor normally hides the underlying Fiber code for you, which makes it really easy to get started.
Meteor.wrapAsync
ensures that a function having a callback with a signature of (error, result)
runs within a Fiber. However, await
is a Promise-based syntax and you cannot use await
to get the result of a Fiber.
In Meteor, it’s fine to mix Fibers with Promises (and async/await
), but it’s important to remember that they are completely different things and you should be aware of how they can be used together.
Consider an aynchronous function getData
, which has a callback with an (error, result)
signature. We can get the result in 4 ways (I’ve ignored error handling for simplicity):
// Get the result in the callback (traditional JavaScript)
getData((error, result) => {
console.log(result); // result is available here
});
// result is undefined (NOT available here)
// Use Meteor's Fibers (traditional Meteor)
const getDataWrapped = Meteor.wrapAsync(getData);
const result = getDataWrapped();
console.log(result);
// Use Promises
const getDataPromise = () => {
return new Promise(resolve => {
getData((error, result) => {
resolve(result);
});
});
}
getDataPromise()
.then(result => {
console.log(result); // Result is available here
)};
// Result is undefined (NOT available here)
// Using async/await
const getDataPromise = () => {
return new Promise(resolve => {
getData((error, result) => {
resolve(result);
});
});
}
const result = await getDataPromise();
You will notice that Meteor’s Fibers and async/await
both result in sync-style programming, where the result is available “inline”.
However, there is a gotcha with async/await
. You must wrap your sync-style await
code in an async function
. Results and “inlining” are only available inside that function.
Finally, on the client, there are no Fibers. You must use callbacks, or wrap callbacks in Promises to use async/await
.
Take a look at these articles, where I go into a bit more depth: