【发布时间】:2019-03-10 07:56:42
【问题描述】:
我是 javascript 中 Promises 的常规用户。现在,我想尝试异步/等待。但是由于对 async/await 的了解一半,我被卡住了。
我有一个使用 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);
}
}
函数转换看起来很简单。但我注意到我的基于 Promise 的代码中有 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;
【问题讨论】:
标签: javascript asynchronous ecmascript-6