async await 的語法可以讓非同步的程式碼看起來像同步一樣。
例如:
async function test(){
  return new Promise((resolve,reject) => {
    reject("test")
  })
}
let res = test();
console.log(res);

將上面的例子加入 await 以及 try catch:
async function test(){
  let testPromise =  new Promise((resolve,reject) => {
    reject("test")
  })
  try{
    let res = await testPromise;
    console.log(testPromise);
  }catch(e){
    console.log(e);
    console.log(testPromise);
  }
}
test();
await 右邊的 testPromise 結果為 reject,所以會進到 catch 區塊
再舉個非同步的例子:
function test(){
  setTimeout(function() {
    throw new Error("Error!!!")
  }, 0);
}
try{
  test()
  console.log("成功")
}catch(e){
  console.log("失敗")
  console.log(e)
}
上面的 test() 裡有 setTimeout function,且裡面寫了 throw Error(),理論上 JavaScript 看到 throw 就要執行 catch 區塊的程式碼了,但因為 setTimeout 是非同步,JavaScript 會先略過它,先往下執行,往下進到 try 區塊裡,所以最終結果顯示:成功。
要處理這樣的問題,就要派上 async await 了。
改寫後的程式碼如下:
await 右邊的要是 Promise,所以將 setTimeout 放到一個 Promise object 中
async function test() {
  let newFunc = new Promise((resolve,reject) => {
    setTimeout(function () {
      reject("Error!!!");
    }, 0);
  })
  try{
    let res = await newFunc;
    console.log(res);
    console.log("成功");
  }catch(e){
    console.log(e);
    console.log("失敗");
  }
}
test()
// Error!!!
// 失敗
參考資料:
https://medium.com/unalai/%E8%AA%8D%E8%AD%98-try-catch-%E8%99%95%E7%90%86%E9%8C%AF%E8%AA%A4-f262d5690820
https://blog.csdn.net/lyyrhf/article/details/115338763