javascriptasync try catch 函数写法,采用=>、返回函数、直接使用函数的三种写法记录如下,这三种写法中的第一、第三其实是一样的,第二总适合reduce或者compose使用。

代码以使用fetch为例。

const format1= (
  async (url) => {
     try{
  console.log("json");
    const res = await fetch(url);
    const json = await res.json();
    console.log(json);
    // [{ name: "张三", age: 18 }, { name: "李四", age: 20 }, { name: "王五", age: 22 }]
  }catch(error) {
        console.log('catch:' + error)
    }
  }
)

format1('https://api.randomuser.me/?nat=US&results=1');

function format2() {
   
  return async (url) => {
    console.log(url);
     try{
  console.log("json");
    const res = await fetch(url);
    const json = await res.json();
    console.log(json);
    // [{ name: "张三", age: 18 }, { name: "李四", age: 20 }, { name: "王五", age: 22 }]
  }catch(error) {
        console.log('catch:' + error)
    }
  }
}

var t=format2();
t('https://api.randomuser.me/?nat=US&results=2');


async  function   format3(url){
      try{
  console.log("json");
    const res = await fetch(url);
    const json = await res.json();
    console.log(json);
    // [{ name: "张三", age: 18 }, { name: "李四", age: 20 }, { name: "王五", age: 22 }]
  }catch(error) {
        console.log('catch:' + error)
    }
}


 
 format3('https://api.randomuser.me/?nat=US&results=10');
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐