Promise的奇怪用法和自己实现一个Promise

Stella981
• 阅读 822

原文链接: Promise的奇怪用法和自己实现一个Promise

使用Promise实现一个页面所有图片加载完毕的回调

import React, { useEffect } from "react";
export default () => {
  useEffect(() => {
    const imageDomList = Array.from(document.getElementsByClassName("image-item"));

    const imagePromiseList = imageDomList.map(
      (i) => new Promise((r) => (i.onload = r))
    );
    const imageLoaded = Promise.all(imagePromiseList);
    imageLoaded.then(() => {
      console.log("所有图片加载完成");
    });
  }, []);

  const imageSrcList = [
    "https://oscimg.oschina.net/oscnet/up-3ebf22d4756e0a1935f2549eeb604f69d2f.gif",
    "https://oscimg.oschina.net/oscnet/up-afc4f6c5faf60f807bed43129a9baaa122a.gif",
  ];
  return (
    <div>
      c1
      {imageSrcList.map((i) => (
        <img class="image-item" key={i} src={i}></img>
      ))}
    </div>
  );
};

将resolve函数提出来

仅演示用, 还有的优化空间, 使用context将resolve函数传递到子组件中, 在子组件完成渲染后调用resolve 通知上层组件渲染完毕

import React, { useEffect, useContext, useState } from "react";

const resolveMapContext = React.createContext({});

const Card = ({ id, time }) => {
  const resolveMap = useContext(resolveMapContext);
  useEffect(() => {
    const r = resolveMap[id];
    console.log("card", id, r);
    setTimeout(() => {
      r && r(id);
    }, time);
  }, [resolveMap]);
  return <div>id:{id}</div>;
};

export default () => {
  const [defaultContext, setDefaultContext] = useState({});

  const cardList = [
    { id: "card1", time: 2000 },
    { id: "card2", time: 4000 },
  ];
  useEffect(() => {
    console.log("App");
    const context = {};
    const cardPromiseList = cardList.map(
      ({ id }) => new Promise((r) => (context[id] = r))
    );

    setDefaultContext(context);
    const cardRendered = Promise.all(cardPromiseList);
    cardRendered.then(() => {
      console.log("所有组件加载完毕");
    });
  }, []);
  return (
    <resolveMapContext.Provider value={defaultContext}>
      <div>
        c1
        {cardList.map(({ id, time }) => (
          <Card key={id} id={id} time={time} />
        ))}
      </div>
    </resolveMapContext.Provider>
  );
};

上述代码有个问题, 在组件切换的时候, 由于promise不能被取消, 所以我们不能在useEffect的return函数中终止promise的执行,当然可以引入变量实现, 不过有更加优雅的方式

自己实现一个Promise, 提供 cancel方法用于取消promise

https://zhuanlan.zhihu.com/p/58428287
https://github.com/YvetteLau/Blog/issues/2
https://juejin.im/post/6844903625769091079

const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";

function resolvePromise(promise2, x, resolve, reject) {
  //PromiseA+ 2.3.1
  if (promise2 === x) {
    reject(new TypeError("Chaining cycle"));
  }
  if ((x && typeof x === "object") || typeof x === "function") {
    let used; //PromiseA+2.3.3.3.3 只能调用一次
    try {
      let then = x.then;
      if (typeof then === "function") {
        //PromiseA+2.3.3
        then.call(
          x,
          (y) => {
            //PromiseA+2.3.3.1
            if (used) return;
            used = true;
            resolvePromise(promise2, y, resolve, reject);
          },
          (r) => {
            //PromiseA+2.3.3.2
            if (used) return;
            used = true;
            reject(r);
          }
        );
      } else {
        //PromiseA+2.3.3.4
        if (used) return;
        used = true;
        resolve(x);
      }
    } catch (e) {
      //PromiseA+ 2.3.3.2
      if (used) return;
      used = true;
      reject(e);
    }
  } else {
    //PromiseA+ 2.3.3.4
    resolve(x);
  }
}

class Promise {
  constructor(executor) {
    this.status = PENDING;
    this.onFulfilled = [];
    this.onRejected = [];

    try {
      executor(this.resolve, this.reject);
    } catch (e) {
      this.reject(e);
    }
  }
  resolve = (value) => {
    if (this.status === PENDING) {
      this.status = FULFILLED;
      this.value = value;
      this.onFulfilled.forEach((fn) => fn()); //PromiseA+ 2.2.6.1
    }
  };

  reject = (reason) => {
    if (this.status === PENDING) {
      this.status = REJECTED;
      this.reason = reason;
      this.onRejected.forEach((fn) => fn()); //PromiseA+ 2.2.6.2
    }
  };
  then = (onFulfilled, onRejected) => {
    //PromiseA+ 2.2.1 / PromiseA+ 2.2.5 / PromiseA+ 2.2.7.3 / PromiseA+ 2.2.7.4
    onFulfilled =
      typeof onFulfilled === "function" ? onFulfilled : (value) => value;
    onRejected =
      typeof onRejected === "function"
        ? onRejected
        : (reason) => {
            throw reason;
          };
    //PromiseA+ 2.2.7
    let promise2 = new Promise((resolve, reject) => {
      if (this.status === FULFILLED) {
        //PromiseA+ 2.2.2
        //PromiseA+ 2.2.4 --- setTimeout
        setTimeout(() => {
          try {
            //PromiseA+ 2.2.7.1
            let x = onFulfilled(this.value);
            resolvePromise(promise2, x, resolve, reject);
          } catch (e) {
            //PromiseA+ 2.2.7.2
            reject(e);
          }
        });
      } else if (this.status === REJECTED) {
        //PromiseA+ 2.2.3
        setTimeout(() => {
          try {
            let x = onRejected(this.reason);
            resolvePromise(promise2, x, resolve, reject);
          } catch (e) {
            reject(e);
          }
        });
      } else if (this.status === PENDING) {
        this.onFulfilled.push(() => {
          setTimeout(() => {
            try {
              let x = onFulfilled(this.value);
              resolvePromise(promise2, x, resolve, reject);
            } catch (e) {
              reject(e);
            }
          });
        });
        this.onRejected.push(() => {
          setTimeout(() => {
            try {
              let x = onRejected(this.reason);
              resolvePromise(promise2, x, resolve, reject);
            } catch (e) {
              reject(e);
            }
          });
        });
      }
    });
    return promise2;
  };
  cancel = () => {
    // console.log("cancel");
    this.status = FULFILLED;
  };
}

Promise.defer = Promise.deferred = function () {
  let dfd = {};
  dfd.promise = new Promise((resolve, reject) => {
    dfd.resolve = resolve;
    dfd.reject = reject;
  });
  return dfd;
};

Promise.resolve = function (param) {
  if (param instanceof Promise) {
    return param;
  }
  return new Promise((resolve, reject) => {
    if (param && param.then && typeof param.then === "function") {
      setTimeout(() => {
        param.then(resolve, reject);
      });
    } else {
      resolve(param);
    }
  });
};

Promise.reject = function (reason) {
  return new Promise((resolve, reject) => {
    reject(reason);
  });
};

Promise.prototype.catch = function (onRejected) {
  return this.then(null, onRejected);
};

Promise.prototype.finally = function (callback) {
  return this.then(
    (value) => {
      return Promise.resolve(callback()).then(() => {
        return value;
      });
    },
    (err) => {
      return Promise.resolve(callback()).then(() => {
        throw err;
      });
    }
  );
};

Promise.all = function (promises) {
  return new Promise((resolve, reject) => {
    let index = 0;
    let result = [];
    if (promises.length === 0) {
      resolve(result);
    } else {
      function processValue(i, data) {
        result[i] = data;
        if (++index === promises.length) {
          resolve(result);
        }
      }
      for (let i = 0; i < promises.length; i++) {
        //promises[i] 可能是普通值
        Promise.resolve(promises[i]).then(
          (data) => {
            processValue(i, data);
          },
          (err) => {
            reject(err);
            return;
          }
        );
      }
    }
  });
};

Promise.race = function (promises) {
  return new Promise((resolve, reject) => {
    if (promises.length === 0) {
      return;
    } else {
      for (let i = 0; i < promises.length; i++) {
        Promise.resolve(promises[i]).then(
          (data) => {
            resolve(data);
            return;
          },
          (err) => {
            reject(err);
            return;
          }
        );
      }
    }
  });
};
module.exports = Promise;
// 跑测试
// npm install -g promises-aplus-tests
// promises-aplus-tests promise.js

测试可以取消的方法以及和原生Promise的兼容性

const CPromise = require("./promise");

const p = new Promise((r) =>
  setTimeout(() => {
    r("p");
  }, 4000)
);

const cp = new CPromise((r) =>
  setTimeout(() => {
    r("cp");
  }, 8000)
);
p.then((v) => console.log("p then", v, new Date().toTimeString()));
cp.then((v) => console.log("cp then", v, new Date().toTimeString()));
Promise.all([p, cp]).then((data) =>
  console.log(data, new Date().toTimeString())
);

setTimeout(() => {
//   cp.cancel();
}, 2000);

/*
调用cancel
p then p 23:51:05 GMT+0800 (China Standard Time)


不调用cancel
p then p 23:51:49 GMT+0800 (China Standard Time)
cp then cp 23:51:53 GMT+0800 (China Standard Time)
[ 'p', 'cp' ] 23:51:53 GMT+0800 (China Standard Time)
*/
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Easter79 Easter79
3年前
swap空间的增减方法
(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
Python之time模块的时间戳、时间字符串格式化与转换
Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。关于时间戳的几个概念时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量。时间元组(struct_time),包含9个元素。 time.struct_time(tm_y
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这