javascript - 我应该从这个异步函数返回什么?
问题描述
我是 javascript 中 Promises 的常规用户。现在,我想尝试异步/等待。但是由于对异步/等待的一半了解,我被困住了。
我有一个使用 Promise 的函数,如下所示:
const asyncRequest = (funcA, b) => {
// do some syncronous stuff. e. g. console.log
console.log(b);
return funcA(b)
.then((something) => console.log(something))
.catch((err) => console.log(err))
}
我试图将上述基于 Promise 的代码转换为 async/await:
const asyncRequest = async (funcA, b) => {
// do some syncronous stuff. e. g. console.log
console.log(b);
try {
const something = await funcA(b);
console.log(something);
} catch (err) {
console.log(err);
}
}
函数转换看起来很简单。但我注意到我return
的基于 Promise 的代码中有关键字。但是在我的异步/等待代码中,我很困惑。我应该返回什么?
真实例子:
基于承诺的例子
const Toast = {};
const createAsyncAction = ({
asyncRequest, types, loadingPayload = null, showToastOnError = true,
}) => (dispatch) => {
dispatch({
type: types.loading,
payload: loadingPayload,
});
return asyncRequest()
.then((response) => {
if (response.isMock) { // if mock request
dispatch({
type: types.success,
payload: response.payload,
});
return;
}
if ([2, 3].includes(String(response.status).substring(0, 1))) { // if request succeeds
response.json()
.then((res) => {
if (res.statusCode === 1000) {
dispatch({
type: types.success,
payload: res.data,
});
return;
}
dispatch({ // if its a known error by server
type: types.failure,
payload: {
code: res.statusCode,
message: res.message,
},
});
if (showToastOnError) {
Toast.error(`${res.statusCode}: ${res.message}`);
}
}).catch((error) => { // if response is not convertible to json
dispatch({
type: types.failure,
payload: {
code: response.status,
message: error.message,
},
});
if (showToastOnError) {
Toast.error(`${response.status}: ${error.message}`);
}
});
return;
}
dispatch((error) => { // if request fails with some status codes like 404, 500...
dispatch({
type: types.failure,
payload: {
code: response.status,
message: error.message,
},
});
if (showToastOnError) {
Toast.error(`${response.status}: ${error.message}`);
}
});
}).catch(() => { // if request cannot be made due to some internet or connection issue
dispatch({
type: types.failure,
payload: {
code: 0,
message: 'Connection issue. Make sure your are connected to the internet and that your API is working',
},
});
if (showToastOnError) {
Toast.error('Connection issue. Make sure your are connected to the internet and that your API is working');
}
});
};
export default createAsyncAction;
异步/等待示例:
const Toast = {};
const createAsyncAction = ({
asyncRequest, types, loadingPayload = null, showToastOnError = true,
}) => async (dispatch) => {
dispatch({
type: types.loading,
payload: loadingPayload,
});
try {
const response = await asyncRequest();
if (response.isMock) { // if mock request
dispatch({
type: types.success,
payload: response.payload,
});
return;
}
if ([2, 3].includes(String(response.status).substring(0, 1))) { // if request succeeds
try {
const jsonResponse = await response.json();
if (jsonResponse.statusCode === 1000) {
dispatch({
type: types.success,
payload: jsonResponse.data,
});
return;
}
dispatch({ // if its a known error by server
type: types.failure,
payload: {
code: jsonResponse.statusCode,
message: jsonResponse.message,
},
});
if (showToastOnError) {
Toast.error(`${jsonResponse.statusCode}: ${jsonResponse.message}`);
}
} catch (error) {
dispatch({
type: types.failure,
payload: {
code: response.status,
message: error.message,
},
});
if (showToastOnError) {
Toast.error(`${response.status}: ${error.message}`);
}
}
return;
}
dispatch((error) => { // if request fails with some status codes like 404, 500...
dispatch({
type: types.failure,
payload: {
code: response.status,
message: error.message,
},
});
if (showToastOnError) {
Toast.error(`${response.status}: ${error.message}`);
}
});
} catch (_) {
dispatch({
type: types.failure,
payload: {
code: 0,
message: 'Connection issue. Make sure your are connected to the internet and that your API is working',
},
});
if (showToastOnError) {
Toast.error('Connection issue. Make sure your are connected to the internet and that your API is working');
}
}
};
export default createAsyncAction;
解决方案
你不需要一个!
任何标记为的函数async
将始终返回一个承诺。现在,如果您希望该承诺解决某些问题,那么您需要返回一个值。但是,由于您只是在做console.log
,它的返回值为undefined
,这相当于什么都不返回(因为undefined
如果没有指定的返回值,JavaScript 将隐式返回)。
从async
文档:
异步函数是通过事件循环异步操作的函数,使用隐式
Promise
返回其结果。
因此,async
将隐式返回包装在 a 中的函数的任何返回值Promise
。
推荐阅读
- jestjs - 在 jest.mock 中需要常量
- angular - 角度材质 - DateRangePicker - 禁用/启用
- markdown - Sphinx Recommonmark CommonMarkParser 未检测到 URL 链接
- python - Django - 无法在页面上显示值
- python - 将geojson文件加载到django数据库中
- r - knitr 更改摘要输出颜色
- docker-compose - Spring cloud gateway 在使用 docker-compose 运行时给出 500 错误 finishConnect(..) failed: Connection refused: localhost/127.0.0.1:8083
- reactjs - 无法在 Outlook Web 加载项项目中安装流畅的 UI 反应
- hunspell - Hunspell 中额外标志的怪癖
- css - 浏览器如何将 Web 元素的颜色的 RGB 格式转换为 RGBA 格式?