How JS elegantly handles async/await exceptions

Neo Fang

Neo Fang

· 1 min read
How to use async/await correctly?

What is async/await

async/await is a new way to write asynchronous programs in JS code. It’s actually syntactic sugar based on Promise, which makes asynchronous code write like synchronous code.

1.Example

Use fetch to get some data asynchronously:

function getData(params){
  return fetch('/api/1', params)
    .then(res1=>{
      return fetch('api/2', res1.id)
        .then(res2=>{
          return res2.detail;
        })
    })
}

Use the async/await:

async function getData(params){
  const res1 = await fetch('/api/1', params);
  const res2 = await fetch('/api/2', res1.id);
  return res2.detail;
}

2.How to handle exceptions

Using try/catch

async function getData(params) {
  let err;
  let res1, res2;
  try {
    res1 = await fetch('/api/1', params);
  }catch (err) {
    console.log('res1 err: ', err);
    err = err;
  }
  if(err) return {err};
  try {
    res2 = await fetch('/api/2', res1.id);
  }catch (err) {
    console.log('res1 err: ', err);
    err = err;
  }
  if(err) return {err};
  return {data: res2};
}

Elegant way

Way 1:

async function getData(params){
  let err;
  try {
    const res1 = await go(fetch('/api/1', params));
    const res2 = await go(fetch('/api/2', res1.id));
  }  catch (err) {
    err = err;
  }
  if(err) return {err};
  return {data};
}

Way2:

async function getData(params){
  let {err, data} = await go(fetch('/api/1', params));
  if(err) return {err};
  let {err: err1, data: data1} = await go(fetch('/api/2', data.id));
  if(err1) return {err: err1};
  
  return {data: data1};
}

Specific implementation of the method go

export default function go (promise, errorExt) {
  return promise
    .then((data) => {data})
    .catch((err) => {
      if (errorExt) {
        const parsedError = Object.assign({}, err, errorExt);
        return {err: parsedError};
      }
      return {err};
    });
}

Thanks for the read!

Writing has always been my passion, and it gives me the pleasure of helping and inspiring people. If you have any questions, feel free to reach out!

Neo Fang

About Neo Fang

Neo is a Front-end technology expert at Alibaba Cloud, as well as being a co-founder of Tarspace.

Copyright © 2024 Terpampas. All rights reserved.
Powered by Vercel