如何调整JS异步事件执行顺序?React Native登录函数返回undefined如何修复
问题根源
你的signIn函数虽然标记了async,但没有返回异步请求的Promise对象:
- 你在
signIn里直接调用了axios.post(),但没有把这个Promise返回,函数默认返回undefined - 所以SignInScreen里的
.then()拿到的是立即返回的undefined,而axios请求是在后续异步完成的,才会打印密钥,这就是你看到输出顺序颠倒的原因。
修复步骤
第一步:修改authService.js的signIn函数
两种写法选一种即可:
写法1:直接返回axios Promise
import axios from "axios"; const signIn = (email, password) => { // 加return把axios的Promise返回出去 return axios .post("http://127.0.0.1:8000/rest-auth/login/", { username: email, email: email, password: password, }) .then((response) => { console.log(response.data.key); return response.data.key; }) .catch((error) => { throw error; // 这里不要直接return error,要抛出才能被上层的catch捕获 }); };
写法2:用async/await语法(更易读)
import axios from "axios"; const signIn = async (email, password) => { try { const response = await axios.post("http://127.0.0.1:8000/rest-auth/login/", { username: email, email: email, password: password, }); console.log(response.data.key); return response.data.key; } catch (error) { throw error; } };
第二步:可选优化SignInScreen的异步写法
你已经把signInUser标记为async,可以统一用await语法,逻辑更清晰:
const signInUser = async (values) => { const { email, password } = values; setSignInLoading(true); try { const response = await signIn(email, password); console.log(response); dispatch({ type: "SIGN_IN", token: response, }); } catch (e) { console.log(e); } finally { setSignInLoading(false); } };
注意点
- 异步函数如果要外部拿到返回结果,必须把内部的异步操作的Promise返回,或者用await等待异步操作完成后再返回结果
- catch块里如果直接return error,上层的then会把error当成正常返回值处理,要抛出错误才能被上层catch捕获
内容的提问来源于stack exchange,提问作者user16372363
相关产品推荐
相关产品推荐

