简体   繁体   中英

Async function with one try catch block

async function handlePersonalInformation(event) {
    event.preventDefault();

    const formData = initialInfo(data);
    try {
      await getPersonalInfo();
      try {
        await updatePersonalInfo(formData);
        alert('Successfully updated!');
      } catch (error) {
        handleError(error);
      }
    } catch (error) {
      try {
        await createPersonalInfo(data);
        alert('Your personal infromation has been saved');
      } catch (error) {
        handleError(error);
      }
    }
  }

I am trying to refactor this function using only one try / catch block. Unfortunately without success.

The problem with this code is that exception thrown by getPersonalInfo is treated as a normal business case: you always go with 'create...' fork if there's an error. Yet I don't think that's the correct implementation: what if that request failed because of some other reason, different from 404?

The better approach seems to be isolating this function, making it only throw real errors:

function wrappedGetPersonalInfo(data) {
  try {
    const res = await getPersonalInfo(data);
    return res;
  } catch (e) { // I wish there were typed catches
    if (e instanceof NotFoundError) { // the check should suit your case
      return null;
    }
    throw e;
  }
}

... then you'll be able to streamline your code quite a lot:

try {
  const res = await wrappedGetPersonalInfo(data);
  if (res) {
    await updatePersonalInfo(formData);
    alert('Successfully updated!');
  }
  else {
    await createPersonalInfo(data);
    alert('Your personal infromation has been saved');
  }
} catch (error) {
  handleError(error);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM