There have been a number of forum posts recently around the topic of working with Promises in Meteor.
I’ve put together a short Medium article on server-side Promises and how they interact with Meteor’s classic Fiber-based coding, including mixing 3rd party Promises with Meteor Promises.
I’m not 100% sure that Medium is the best tool for technical articles, but here it is anyway. Feedback welcomed!
Hey I think this is something that would be cool to have a post about on the official Medium blog - do you want to collaborate on a post there? We can go into some other ideas, such as Promise.await (a way to convert any promise into fiber code, without the await syntax), and I also think you can use Promise.resolve(otherPromise) to convert between promise libraries more easily!
Great article! I have myself encountered the issue a few days ago.
I would also add, if you don’t need to write in a Mongo collection the result of the promise and only return it to client, you can use promises without any trouble:
Meteor.methods({
myMethod: function () {
return api.create({
...
}).then((res) => {
console.log('Promise resolved', res);
return res;
}).catch((e) => {
console.log('Promise failed', e);
throw new Meteor.Error(500, 'There was an error processing your request');
});
}
})
As @sashko mentionned, we can also use Promise.await() inside a try catch block to make the promise synchronous.
Anyways, an post on the official blog would be really helpful for other devs as this is a common issue.
Great article! And much needed. With some NPM packages, due to how the packages were created & interactions with Meteor, I had to nest a number of promises just to get them working, which is not only confusing but also led to very messy looking code.
This, in my opinion, is the weakest aspect of Meteor’s NPM support.
@robfallows this was a great article and you must take @sashko on his offer because I was trying to solve an async/await problem for a friend this morning where
async function foo() { return await bar(); }
kept throwing errors about meteor code needing to be run within a fiber and whatever I did (wrapasync/bindenvironment et al) within bar() or foo() did not help.
And finally, I remembered this thread and did
function foo() { return Promise.await bar(); }
and voila!
And then I tried to find some meteor documentation about async/await and that special promise but there was none I could find.
Furthermore, it seems there’s no documentation about things like webappinternals, mongointernals and httpinternals either. I’m sure there are other things that meteor has to offer yet undocumented. @sashko what can we do about such things?