JS实用篇复习笔记(12)

155 阅读2分钟

1、常规捕获错误

1、try...catch

try {

  // code...

} catch (err) {

  // error handling
  • 通常 必须执行的步骤 放在 finally中
try {
   ... try to execute the code ...
} catch (err) {
   ... handle errors ...
} finally {
   ... execute always ...
}
  • try内有 return 先执行 finally 里的部分
function func() {

  try {
return 1;            // 2

  } catch (err) {
    /* ... */
  } finally {
alert( 'finally' ); //  1
  }
}

alert( func() ); // first works alert from finally, and then this one
  • 全局错误
window.onerror = function(message, url, line, col, error) {
  // ...
};

2、抛出错误

new throw Error('xxx')

3、 console.error('xxx')

2、基本Promise

  • 基本样子
let promise = new Promise((resolve,reject) => {

    })
  • 成功的样子
    let promise = new Promise((resolve, reject) => {
      setTimeout(() => resolve("done"), 1000);
    });

image.png

  • 失败的样子
 let promise = new Promise((resolve, reject) => {
      setTimeout(() => reject(new Error("some Errors")), 1000);
    });

image.png

  • 不管成功失败 只能存在一个情况 下面两个 ignored很重要
let promise = new Promise(function(resolve, reject) {
resolve("done");

  reject(new Error("…")); // ignored
  setTimeout(() => resolve("…")); // ignored
});
  • 获得立即值
let promise = new Promise(function(resolve, reject) {
  // not taking our time to do the job , not wait
  resolve(123); // immediately give the result: 123
});
  • 继续执行 .then
promise.then(
  function(result) {  /* handle a successful result */  },
  function(error) {  /* handle an error */  }
);

// 箭头函数 表达
 // resolve runs the first function in .then
promise.then(
  result => alert(result), // shows "done!" after 1 second
  error => alert(error) // doesn't run
);

* .catch 捕获错误

// .catch(f) is the same as promise.then(null, f)
promise.catch(alert);

* .finally 肯定执行

.finally(() => alert("Promise ready"))
  • 经典问题1 打印结果
//只打印1 

// The second call to `resolve` is ignored, because only the first call of `reject/resolve` is taken into account. Further calls are ignored

let promise = new Promise(function(resolve, reject) {
  resolve(1);  // 1
 
  setTimeout(() => resolve(2), 1000);
});

promise.then(alert);
  • 经典问题2 经过ms 输出什么内容
    function delay(ms) {
      return new Promise((resolve) => setTimeout(resolve, ms));
    }

    delay(3000).then(() => alert("runs after 3 seconds"));

3、Promise链条

new Promise(function (resolve, reject) {
  setTimeout(() => resolve(1), 1000); // (*)
})
  .then(function (result) {
    // (**)

    alert(result); // 1
    return result * 2;
  })
  .then(function (result) {
    // (***)

    alert(result); // 2
    return result * 2;
  })
  .then(function (result) {
    alert(result); // 4
    return result * 2;
  });
  • 流程图

image.png

  • thenable 函数 函数内有then 方法

  • 或者说 实现了一个 then方法 并对此方法 进行调用

    // thenable函数
    class Thenables {
      constructor(num) {
        this.num = num;
      }
      then(resolve, reject) {
        alert(resolve);
        setTimeout(() => resolve(this.num * 2), 1000);
      }
    }

    new Promise((resolve) => resolve(1))
      .then((result) => {
        return new Thenables(result);
      })
      .then(console.log); // 1s后打印出内容

4、Promise实践之 fetch

  • fetch 结果为一个 promise
let promise = fetch(url);

* 常用 fetch 结构

// same as above, but response.json() parses the remote content as JSON
fetch('/article/promise-chaining/user.json')
  .then(response => response.json()) // 先转为 json 才能 在后续的.then拿到数据 
  .then(user => alert(user.name)); // iliakan, got user name

* promise 应用 结果

image.png

  • 经典问题之 这两个区别在哪 ?

  • 第一个出错 catch捕获 第二个 没有捕获流程

promise.then(f1).catch(f2);
promise.then(f1, f2);

5、进化篇之 async await

  • await 必须放在 async 中使用
  • 声明异步方法 只需在前面 加上 async
    async () => {
      let response = await fetch("/article/promise-chaining/user.json");
      let user = await response.json();
      // 后续可对 这个转为 json的user 进行处理 
    };
  • 错误处理策略
    // 1
    async function f() {
      await Promise.reject(new Error("some error"));
    }

    // 2
    async function f() {
      new Error("some error");
    }

    // 3
    async function f() {
      try {
        let response = await fetch(url);
        let user = response.json();
      } catch (e) {
        console.log(e);
      }
    }
    f();

*经典转化 promise---> async/await

    // 经典问题 将.then ---> 转为 async/await
    function loadJson(url) {
      return fetch(url).then((response) => {
        if (response.status == 200) {
          return response.json();
        } else {
          throw new Error(response.status);
        }
      });
    }

    async function loadJson(url) {
      //(1)
      let response = await fetch(url); //(2)
      if (response.status == 200) {
        let json = await response.json(); //(3)
        return json;
      }
      throw new Error(response.status);
    }