如何在调用API的函数中返回承诺



我有一个调用API的函数,我希望它返回一个承诺,这样我就可以知道它什么时候完成执行

这是我的组件,我调用函数

import { login } from "../../redux/apiCalls";
...
const handleLogin = async (e) => {
e.preventDefault();
login(email, password, dispatch);
history.push('/admin');
}

这里是函数本身(这里我使用redux)

export const login = async (email, password, dispatch) => {
try {
dispatch(loginStart());
const res = await axios.post('myserver...', {
email: email,
password: password,
});
dispatch(loginSuccess(res.data));
} catch (err) {
dispatch(loginError());
}
}

使用async默认设置此行为,该函数返回一个promise,等待或不等待,因此您可以此

const handleLogin = async (e) => {
e.preventDefault();
await login(email, password, dispatch);
history.push('/admin');
}

如果发生错误,你必须在async函数

中选择try catch
const handleLogin = async (e) => {
e.preventDefault();
try {
await login(email, password, dispatch);
history.push('/admin');
} catch(err) {console.log("Hey this is an error baby ;)", err)}
}

,但我真的不喜欢等待承诺的想法,因为javascript是单线程,所以我建议使用。then() .catch()

const handleLogin = (e) => {
e.preventDefault();
return login(email, password, dispatch).then(() => {
history.push('/admin');
}).catch(console.log);
}

这里线程没有阻塞,但也许你想要它阻塞,所以…由你决定

最新更新