5

我只是想知道如何在函数中实现回调onPress函数。我想确保第一个功能完成,然后触发第二个过程。

onPress={() => {
          onSignIn(); //run this function first
          if(_values.success == 1){ //then run this after onSignIn() function completed
            navigation.navigate("SignedIn");
          } 
        }}

登录()

export const onSignIn = async () => {
  if (_values.username && _values.password) { 
    fetch("http://localhost:3001/sessions/create", {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: _values.username,
        password: _values.password
      })
    })
    .then((response) => response.json())
    .then((responseData) => {
      if(responseData.access_token){
         AsyncStorage.setItem(USER_KEY, responseData.access_token);
        _values.success = 1;
        alert("Login successfully!");
        return _values.success;
      } else {
        alert("Wrong username and password!");
        _values.success = 0;
        return _values.success;
      }
    })
    .done();
  } else{
    alert("Please enter your username and password.");
  }
}

参考:https ://github.com/datomnurdin/auth-reactnative

4

4 回答 4

2

从方法中返回一个 Promise 并将 .then() 添加到函数调用中

export const onSignIn = async () => {

  const promise =  new  Promise(async (resolve, reject) => {

    try {
    //do something and return result on success
    resolve(result);

   }catch(msg) { reject(msg);}

   });

  return promise;
}

像这样调用方法:

onSignIn ().then(
     (response,error) => {
     //get callback here
  });
于 2020-06-02T11:30:15.020 回答
2

“等待onSignIn完成”我猜你的意思是它是一个异步函数,然后你可以使用await运算符等待它结束

onPress={() => {
        await onSignIn(); //run this function first
        if(_values.success == 1){ //then run this after onSignIn() function completed
            navigation.navigate("SignedIn");
        } 
    }}

然后你将不得不添加async到你的 onSignIn 函数中:

onSignIn = async () => {console.log("signing in")}

这是一种更“React-y”的方式也可以处理您的整个过程:

import React, { Component } from 'react'

export default class Example extends Component {

    onSignIn = async () => {
        console.log('singing in....')
    }

    pressEvent = async event => {
        await this.onSignIn(); //run this function first
        if (_values.success == 1) { //then run this after onSignIn() function completed
            navigation.navigate("SignedIn");
        }
    }

    render() {
        return (
            <div onPress={this.pressEvent}>

            </div>
        )
    }
}

编辑 :

您可以简单地在函数中返回一个布尔值,而不是返回 0 或 1。此外,现在您使用的是更现代的async/await运算符,您可以删除这些then函数:

export const onSignIn = async () => {
    if (_values.username && _values.password) {
        const response = await fetch("http://localhost:3001/sessions/create", {
            method: "POST",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username: _values.username,
                password: _values.password
            })
        })
        const responseData = JSON.parse(response)
        if (responseData.access_token) {
            AsyncStorage.setItem(USER_KEY, responseData.access_token);
            alert("Login successfully!");
            return true
        } else {
            alert("Wrong username and password!");
            return false
        }
    } else {
        alert("Please enter your username and password.");
    }
}

现在,您将如何从该函数中获取响应:

export default class Example extends Component {

    pressEvent = async event => {
        if (await onSignIn()) navigation.navigate("SignedIn");
    }

    render() {
        return (
            <div onPress={this.pressEvent}>

            </div>
        )
    }
}
于 2018-12-26T15:12:32.267 回答
0

这段代码应该可以帮助你

async onPressFunc() {
  await onSignIn(); //run this function first

  if(_values.success == 1){ //then run this after onSignIn() function completed
    navigation.navigate("SignedIn");
  } 
}

onPress={this.onPressFunc}
于 2018-12-26T15:01:56.227 回答
0

首先, onSign() 必须是一个async函数,不要添加done()函数,你想在后面处理它:

  export const onSignIn = async () => {
  if (_values.username && _values.password) { 
    fetch("http://localhost:3001/sessions/create", {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: _values.username,
        password: _values.password
      })
    })
    .then((response) => response.json())
    .then((responseData) => {
      if(responseData.access_token){
         AsyncStorage.setItem(USER_KEY, responseData.access_token);
        _values.success = 1;
        alert("Login successfully!");
        return _values.success;
      } else {
        alert("Wrong username and password!");
        _values.success = 0;
        return _values.success;
      }
    })
  } else{
    throw "Please enter your username and password.";
  }
}

然后,您只需执行以下操作:

onPress={() => {
          onSignIn().then( (values) => {
            if(values.success == 1){
               navigation.navigate("SignedIn");
            } 
          })
          .catch(error => console.log(error)) //do something in case onSignIn fails 
        }}
于 2018-12-26T14:59:16.307 回答