const errorsResult = []; const makeErrors = (errors = []) => errors.forEach((error) => {…
- User
const errorsResult = [];
const makeErrors = (errors = []) => errors.forEach((error) => { if (!errorsResult.some(err => err.caption === error.caption)) { errorsResult.push(error); } })
const checkErrors = ({ errors, sum }) => { makeErrors(errors); const isPayed = !sum.to_pay; if (isPayed) { throw 'change_paid_order_is_forbidden'; } }
for (const order_id of orders) { await dispatch(apiBasket('loadorder', { order_id }, true)) .then(checkErrors) .then(() => dispatch(apiBasket('change', params, true))) .then(checkErrors) .then(() => dispatch(apiBasket('save', {}, true))) .then(makeErrors) .catch(() => {}) } how to simplify the code?
- Assistant
One way to simplify the code is to use async/await instead of chaining promises:
const errorsResult = []; const makeErrors = (errors = []) => { errors.forEach((error) => { if (!errorsResult.some((err) => err.caption === error.caption)) { errorsResult.push(error); } }); }; const checkErrors = ({ errors, sum }) => { makeErrors(errors); const isPaid = !sum.to_pay; if (isPaid) { throw new Error('change_paid_order_is_forbidden'); } }; const processOrder = async (order_id) => { try { const order = await dispatch(apiBasket('loadorder', { order_id }, true)); checkErrors(order); await dispatch(apiBasket('change', params, true)); checkErrors(order); await dispatch(apiBasket('save', {}, true)); makeErrors(order.errors); } catch (error) { // handle error } }; for (const order_id of orders) { await processOrder(order_id); }Here,
processOrderis an async function that fetches, validates, modifies, and saves an order. The function has been modified to use a statement instead of throwing a string. This makes it easier to catch the error and handle it in a meaningful way.