简体   繁体   English

React ES6:从另一个未定义的函数调用异步函数

[英]React ES6: calling async function from another function not defined

This is where I call register() :这是我调用register()

this.register();

Here's the register() :这是register()

register = async () => {
    await login();
    await create();
}

Here are the ones I call:以下是我所说的:

login = () => {
    console.log('test');
}

Ideally, what I want is to finish login() first, then go to create() .理想情况下,我想要的是先完成login() ,然后再去create()

Error I get:我得到的错误:

Uncaught (in promise) ReferenceError: login is not defined Uncaught (in promise) ReferenceError: login is not defined

As stated in the comments, you will probably need to complete the question with more context. 如评论中所述,您可能需要更多背景来回答问题。 In general, in Javascript, if you are working with classes, you will need to bind the context: 通常,在Javascript中,如果要使用类,则需要绑定上下文:

this.login = this.login.bind(this)

and then call this.login() 然后调用this.login()

Moreover, in the case of react/redux , if your login function is not in your component you will probably have to connect your component and tell Redux what is the function you'll use, as explained here: Redux - call action from a function 而且,在react/redux的情况下,如果您的login功能不在组件中,则可能必须connect您的组件,并告诉Redux您将使用什么功能,如下所述: Redux-从函数调用操作

I had this issue when I was calling a normal function inside an Async function.我在 Async 函数中调用普通函数时遇到了这个问题。 Even though the async function was called directly on the button click, it still needed binding ( this.function= this.function.bind(this) ).即使直接在按钮点击时调用异步函数,它仍然需要绑定( this.function= this.function.bind(this) )。 The function I was calling did not need Binding itself, which wasn't consistent with what I've encountered before with binding.我正在调用的函数不需要绑定本身,这与我之前遇到的绑定不一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM