我只是想知道如何在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.");
}
}
最佳答案
从方法中返回一个 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
});
关于javascript - 如何在 React Native 中实现回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53933642/