Meteor:使用异步方法

时间:2017-11-10 13:07:37

标签: meteor async-await meteor-methods

我正在使用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我有错误==未定义,但在index.js(反应部分)里面是errorClass。

我们如何处理Meteor方法中的异步代码?

1 个答案:

答案 0 :(得分:2)

我明白了。为什么我在客户端上使用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。

Inside React我也使用异步语法:



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

    }