2

我正在将 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!
        //     }
        // });
    }
});
注意:Meteor.loginWithGoogle 由 accounts-google 包提供。测试时,我能够导航到谷歌登录页面,登录并重定向回我的应用程序),然后打印日志。

这里注释的代码是旧方法。请注意,我有带有数字的 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 方法中的异步代码?

4

1 回答 1

3

我知道了。为什么我在客户端使用 Meteor.methods?我可以像这样使用javascript函数:

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
}

我只是使用异步函数,它返回 Promise。

在 React 内部,我也使用异步语法:

async loginWithGoogle() {
        let err = await loginWithGoogle()
        if (err){
            console.log(err)
        }else {
            console.log('success')
        }

    }

于 2017-11-10T14:08:44.577 回答