将 redux Promise 函数反应到 async/await
react redux Promise function to async/await
我有以下 redux 函数将新用户添加到我的数据库中。它工作正常,但如果我在我的 then
中引入另一个调用,可能需要对所有内容进行广泛的捕获。
如果我们将它变成 async
和 try/Catch
来处理我们所有的错误呢?
我尝试了一个样本,但一直遗漏了一些东西。
有人可以帮我安排一下吗?谢谢。
export function newUser(values) {
return function(dispatch) {
const promise = axios.post(URL)
dispatch(createAdminUsersRequest(promise));
promise.then(
user => {
dispatch(createUsersSuccess(user));
dispatch(fetchUsers());
dispatch(switchUserActions(false, false, false));
},
function(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
dispatch(createUsersFail(errors(error)));
setTimeout(() => dispatch(createUsersFail(null)), 6000);
}
);
return promise;
};
}
将 promise 转换为 async-await 非常简单。首先,通过向其添加 async
关键字将函数声明为 async
。其次,你在 promise
上使用 await
export function newUser(values) {
return async function(dispatch) {
dispatch(createAdminUsersRequest(promise));
try {
const user = await axios.post(URL);
dispatch(createUsersSuccess(user));
dispatch(fetchUsers());
dispatch(switchUserActions(false, false, false));
} catch(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
dispatch(createUsersFail(errors(error)));
setTimeout(() => dispatch(createUsersFail(null)), 6000);
}
};
}
我有以下 redux 函数将新用户添加到我的数据库中。它工作正常,但如果我在我的 then
中引入另一个调用,可能需要对所有内容进行广泛的捕获。
如果我们将它变成 async
和 try/Catch
来处理我们所有的错误呢?
我尝试了一个样本,但一直遗漏了一些东西。
有人可以帮我安排一下吗?谢谢。
export function newUser(values) {
return function(dispatch) {
const promise = axios.post(URL)
dispatch(createAdminUsersRequest(promise));
promise.then(
user => {
dispatch(createUsersSuccess(user));
dispatch(fetchUsers());
dispatch(switchUserActions(false, false, false));
},
function(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
dispatch(createUsersFail(errors(error)));
setTimeout(() => dispatch(createUsersFail(null)), 6000);
}
);
return promise;
};
}
将 promise 转换为 async-await 非常简单。首先,通过向其添加 async
关键字将函数声明为 async
。其次,你在 promise
await
export function newUser(values) {
return async function(dispatch) {
dispatch(createAdminUsersRequest(promise));
try {
const user = await axios.post(URL);
dispatch(createUsersSuccess(user));
dispatch(fetchUsers());
dispatch(switchUserActions(false, false, false));
} catch(error) {
if (error && error.response && error.response.data)
error = error.response.data;
if (error && error.data) {
error = error.data;
}
dispatch(createUsersFail(errors(error)));
setTimeout(() => dispatch(createUsersFail(null)), 6000);
}
};
}