Reputation: 3048
I am using React with Meteor. I have a method inside React component that calls Meteor.method (which is run on client as well):
// index.js
loginWithGoogle() {
console.log('1')
Meteor.call('auth.loginWithGoogle', {}, (err, res)=>{
console.log('5');
if (err) {
console.log(err) // line 16:
} else {
console.log('success');
// console.log(res);
// console.log('logged in with google callback in react yay:)')
}
});
}
In client side Meteor I have method:
// auth.js
Meteor.methods({
async 'auth.loginWithGoogle'(){
console.log('2')
let err = await Meteor.loginWithGoogle()
console.log('3');
console.log(err)
if (err) {
console.log('-1')
throw new Error(err);
}
console.log('4');
// Meteor.loginWithGoogle({
// // options
// }, (err) => {
// console.log('3')
// if (err) {
// console.log(err)
// throw new Meteor.Error(err)
// } else {
// console.log('4')
// // successful login!
// }
// });
}
});
Here the commented code is old approach. Notice, I have console.log calls with numbers, the numbers indicate the order in which I expect code to be executed. The old method does not work at all, console.log('5') runs earlier than (3 and 4), due to asynchronous execution. Rewriting with async/await gives this:
index.js:12 1
auth.js:4 2
auth.js:6 3
auth.js:7 undefined
auth.js:12 4
index.js:14 5
index.js:16 errorClass {isClientSafe: true, error: 404, reason: "Method 'auth.loginWithGoogle' not found", details: undefined, message: "Method 'auth.loginWithGoogle' not found [404]", …}
So, from logs I can see that code is executed as i expected. Inside auth.js:7 I have err == undefined, but inside index.js (react part) it is errorClass.
How do we deal with async code in Meteor methods?
Upvotes: 2
Views: 2799
Reputation: 3048
I got it. Why I was using Meteor.methods on client? I could just use javascript function like that:
const loginWithGoogle = async () => {
console.log('2')
let err = await Meteor.loginWithGoogle()
console.log('3');
console.log(err)
if (err) {
console.log('-1')
throw new Error(err);
}
console.log('4');
}
export {
loginWithGoogle
}
I just use async function, it returns Promise.
Inside React I use async syntax too:
async loginWithGoogle() {
let err = await loginWithGoogle()
if (err){
console.log(err)
}else {
console.log('success')
}
}
Upvotes: 4