无法同步并等待正常工作

时间:2019-06-20 17:28:15

标签: react-native async-await axios

我正在尝试进行登录/创建帐户屏幕,但是我无法使异步程序正常运行。 Await无法正常工作,我的控制台在调用authToken后立即打印未定义的内容,然后打印“关于调用saveUserToken的信息”。

点击“创建帐户”按钮后,我称呼它。

async createUser() { 
        if ((this.state.email != "" && this.state.fname != "" && this.state.lname != "" && this.state.password != "" && this.state.confirmPassword != "")) {
            if (this.state.password == this.state.confirmPassword) {

                const authToken = await QueryHandler.createUser(this.state.email, this.state.password, this.state.fname, this.state.lname);
                console.log(authToken);

                console.log('About to call saveUserToken');
                const storeToken = await SecureDataStorage.saveUserToken(authToken);
                console.log(storeToken);

                ToastHandler.displayNormalMessage('Stored Token');
                const t = await SecureDataStorage.getUserToken();
                console.log('Got from SecureStorage:' + t)
                if(r) {
                    //Succesful result...
                    ToastHandler.displayNormalMessage('Account Created!');
                } else {
                    //Error...
                    ToastHandler.displayErrorMessage('Could not Create Account');
                }

                //Then navigate to login screen...

            } else {
                ToastHandler.displayErrorMessage('Passwords do not Match')
            }
        } else {
            ToastHandler.displayErrorMessage('Please Fill in all Fields');
        }
    }

This is my create user method.

static createUser(e, p, f, l) {
    result = '';
    axios.post((GRAPHQL_END_POINT), {
      query: print(Queries.CREATE_USER),
      variables: {
        firstName: f,
        lastName: l,
        email: e,
        password: p
      }
    })
      .then(res => {
        this.result = res.data.data.createUser.jwt;
        console.log(this.result);
        return true;
        // console.log(this.result);
      })
      .catch(err => {
        console.log(err)
        return false;
      })
      // return this.result;
  }

2 个答案:

答案 0 :(得分:0)

问题可能出在Gmodel.find({data.data_type: "event"}, callbackFunction) 。如果它是异步的,请确保它在返回结果之前等待结果。

答案 1 :(得分:0)

您应该尝试使createUser异步,以免将诺言与异步语法混淆。

    async createUser(e, p, f, l) {
    const res = await axios.post((GRAPHQL_END_POINT), {
      query: print(Queries.CREATE_USER),
      variables: {
        firstName: f,
        lastName: l,
        email: e,
        password: p
      }
    })
    console.log('res', res)
    return res.data.data.createUser.jwt;
  }
相关问题