对Promise逐渐认知

Promisethencatchfinally都会返回自身Promise的引用

    console.log('then',Promise.resolve().then());
    console.log('catch',Promise.resolve().catch());
    console.log('finally',Promise.resolve().finally());


这一点对封装基础逻辑的ajax请求很有帮助

下面两种写法有啥区别

    Promise.reject().then(
      (res) => {},
      (rej) => {
        console.log("发生错误");
      },
    );

    Promise.reject()
      .then((res) => {})
      .catch((rej) => {
        console.log("发生错误");
      });

Promise.prototype.catch方法是.then(null, rejection).then(undefined, rejection)的别名,用于指定发生错误时的回调函数

虽然都会输出=>发生错误,但是第二种方法还会捕获then 里面的错误

    Promise.resolve().then(
      (res) => {
        throw new Error("抛出异常");
      },
      (rej) => {
        console.log("发生错误");
      },
    );
    Promise.resolve()
      .then((res) => {
        throw new Error("抛出异常");
      })
      .catch((rej) => {
        console.log("发生错误");
      });

结果为:


axios 实现了Promise 规范
race 表示 哪个结果获得的快,就返回那个结果,不管结果本身是成功状态还是失败状态。
结合一下:

Promise.race([
      axios.post("/test/test/test2"),
      axios.post("/test/test/test1"),
    ]).then((r1) => {
      console.log("res", r1);
    });

我之前一直以为race 表示哪个成功用哪个,开发时候没涉及到这种场景,竟然就这么过来了...

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容