2

I have the following code:

for (const element of elements) {
  try {
    // eslint-disable-next-line no-await-in-loop
    const { a, b, c, d, e } = await func(element.id);

    if (tokens.includes(a)) {
      saveElement("a", a, element.id); // First arg is the key as string
      break;
    }

    if (tokens.includes(b)) {
      saveElement("b", b, element.id);
      break;
    }

    ...

    if (tokens.includes(e)) {
      saveElement("e", e, element.id);
      break;
    }
  } catch (err) {
    console.error(err);
  }
}

As you can imagine, there might be a way to avoid this long if statement queue... If you see, there is some kind of pattern in the code, where the only things which are different are the fields destructured from the result of func().

Is there any way to make this cleaner? I mean, to avoid the spaghetti code.

Thank you.

1 Answer 1

2

Iterate over an array of property names instead, and use .find to find the first matching one, if any:

const properties = ['a', 'b', 'c', 'd', 'e'];
for (const { id } of elements) {
  try {
    // eslint-disable-next-line no-await-in-loop
    const obj = await func(id);
    const prop = properties.find(prop => tokens.includes(obj[prop]));
    if (prop) {
      saveElement(prop, obj[prop], id);
    }
  }

No need for break anymore.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.