按顺序调用异步函数,加载直到完成



我需要调用多个异步函数来完成React Native应用程序中的用户登录。问题是,我的登录在这些异步功能完成之前就被调度了,并且在API中的数据完全保存之前就加载了主屏幕。这是我的代码中获取API数据和调度登录的部分:

// Login and retrieve the authtoken, username, and uid, then save to SecureStore
await axios.post(
'/login', 
JSON.stringify({
'username': data.username,
'password': data.password
}),
{
headers: {'Content-Type': 'application/json'}
}
)
.then(res => {
// Save uid, auth token, and username to securestore
// These need to complete before dispatching SIGN_IN
saveUserInfo(res.data.uid, res.data.token, data.username);
getAppScreensFromAPI(res.data.token, res.data.uid);
dispatch({ type: 'SIGN_IN', token: res.data.token });
})

在调度SIGN_IN之前,我如何构造此代码以完成异步功能?我想在后台设置一个状态来显示加载屏幕,但我不知道异步函数完成后如何写入代码。

以下是我在.then():中使用的异步函数的代码

// Save the uid, auth token, and username to SecureStore
async function saveUserInfo(uid, token, username) {
// Convert all user info to String data type before saving to SecureStore
let uid_str = uid.toString();
let token_str = token.toString();
let username_str = username.toString();
await SecureStore.setItemAsync('userToken', token_str);
await SecureStore.setItemAsync('username', username_str);
await SecureStore.setItemAsync('uid', uid_str)
}
export async function getAppScreensFromAPI(userToken, uid) {
const response = await axios.get(
('/personnel/app_screens/' + uid),
{
headers: {'Authorization': 'Token ' + userToken}
}
)
// Save the JSON data for the app_screens list as a string to be parsed later
await AsyncStorage.setItem('app_screens', JSON.stringify(response.data));
// Return the app_screens array
return response.data.app_screens;
}

如果我的代码一团糟,我深表歉意,这是一个令人沮丧的学习过程。我想我误解了异步函数的工作方式,但我很难找到我需要的信息。

在您的示例中,在'then'代码同步运行之后,您需要在异步运行之后发出这些指令,例如:

// Login and retrieve the authtoken, username, and uid, then save to SecureStore
try {
const res = await axios.post(
'/login',
JSON.stringify({
'username': data.username,
'password': data.password
}), {
headers: {
'Content-Type': 'application/json'
}
}
)
// Save uid, auth token, and username to securestore
// These need to complete before dispatching SIGN_IN
await saveUserInfo(res.data.uid, res.data.token, data.username);
await getAppScreensFromAPI(res.data.token, res.data.uid);
dispatch({
type: 'SIGN_IN',
token: res.data.token
});
} catch (err) {
console.log(err);
//Maybe dispatch an error here
//dispatch({ type: 'SIGN_IN_ERROR', err });
}

您可以使then回调async按顺序执行函数

// Login and retrieve the authtoken, username, and uid, then save to SecureStore
await axios.post(
'/login', 
JSON.stringify({
'username': data.username,
'password': data.password
}),
{
headers: {'Content-Type': 'application/json'}
}
)
.then(async res => {
// Save uid, auth token, and username to securestore
// These need to complete before dispatching SIGN_IN
await saveUserInfo(res.data.uid, res.data.token, data.username);
await getAppScreensFromAPI(res.data.token, res.data.uid);
dispatch({ type: 'SIGN_IN', token: res.data.token });
})

最新更新