我正在将 React 与 Meteor 一起使用。我在 React 组件中有一个调用 Meteor.method 的方法(它也在客户端上运行):
// 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:)')
}
});
}
在客户端 Meteor 我有方法:
// 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!
// }
// });
}
});
这里注释的代码是旧方法。请注意,我有带有数字的 console.log 调用,数字表示我期望代码执行的顺序。旧方法根本不起作用,console.log('5') 运行早于(3 和 4),由于异步执行。用 async/await 重写给出了这个:
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]", …}
因此,从日志中我可以看到代码按预期执行。在 auth.js:7 里面我有 err == undefined,但是在 index.js(反应部分)里面是 errorClass。
我们如何处理 Meteor 方法中的异步代码?