Javascript 编写此代码的更好方法?我试图避免使用双返回语句
这段代码可以工作,但我不知道如何在不破坏逻辑的情况下编写得更好。我试着用三元数,但没有用。我们能更好地表述这一点吗?我对双倍返回不满意。是的,您可以重写它以避免“双倍返回”。然而,我不确定这样做会有多好。在Javascript 编写此代码的更好方法?我试图避免使用双返回语句,javascript,reactjs,react-native,ecmascript-6,Javascript,Reactjs,React Native,Ecmascript 6,这段代码可以工作,但我不知道如何在不破坏逻辑的情况下编写得更好。我试着用三元数,但没有用。我们能更好地表述这一点吗?我对双倍返回不满意。是的,您可以重写它以避免“双倍返回”。然而,我不确定这样做会有多好。在中使用else,如果中有数据,则使具有更大的范围和默认值。像 async function formulateResponse({ response, input }) { if (response.statusText === 'No Content') { return {
中使用else
,如果中有数据
,则使具有更大的范围和默认值。像
async function formulateResponse({ response, input }) {
if (response.statusText === 'No Content') {
return {
id: input.customerId,
paymentMethods: [],
};
}
if (response.statusText !== 'OK') throw new Error(await parseResponseErrors(response));
const data = await response.json();
return {
id: input.customerId,
paymentMethods: data,
};
}
这一点也不好
async function formulateResponse({ response, input }) {
data = [];
if (response.statusText === 'No Content') {
// do nothing
} else if (response.statusText !== 'OK') {
throw new Error(await parseResponseErrors(response));
} else {
data = await response.json();
}
return {
id: input.customerId,
paymentMethods: data,
};
}
也许可以将此发布到codereview.stackexchange.com?不幸的是,这里没有讨论这个问题,因为代码没有什么问题(任何提出的“更好”的方法实际上都只是意见)。
async function formulateResponse({ response, input }) {
const defaultPaymentMethods = [];
if (['OK', 'No Content'].indexOf(response.statusText === -1) {
throw new Error(await parseResponseErrors(response));
}
return {
id: input.customerId,
paymentMethods: response.statusText === 'OK' ? await response.json().data : [];
};