//promise里面只有三个状态,且三个状态的转换形式有两种
//由pending转换为fulfilled,由pending转换为rejected //Promise的构造函数参数是一个函数,函数的参数分别为resolve和reject,两者也均为一个函数
//then中是实际要执行的函数,将传递进来的值传给resolve和reject对应的参数
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'
class YPromise {
constructor(cb) {
this.state = PENDING;
this.value = null;
//承诺完成的回调列表
this.fulfilledCbs = [];
//承诺被拒绝的回调列表
this.rejectedCbs = []; let resolve = data => {
setTimeout(() => {
if (this.state !== PENDING) return;
//更改状态
this.state = FULFILLED;
this.value = data;
this.fulfilledCbs.forEach(c => {
this.value = c(this.value);
}) }, 0); }
let reject = reason => {
setTimeout(() => {
if (this.state !== PENDING) return;
this.state = REJECTED;
this.reason = reason;
this.rejectedCbs.forEach(c => {
this.reason = c(this.reason);
}) }, 0);
}
cb(resolve, reject);
};
then(onFulfilled, onRejected) {
if (typeof onFulfilled === 'function') {
this.fulfilledCbs.push(onFulfilled);
}
if (typeof onRejected === 'function') {
this.rejectedCbs.push(onRejected);
}
return this;//返回整个构造函数可以继续调用then方法
}
} let promise = new YPromise((resolve, reject) => {
if (4 > 1) {
resolve('hi');
} else {
reject(4大于1')
}
}) fulfilledCbs = [data => data + 'world']
promise.then(data => {
return data + ' world';
}).then(data => {
return data + '!';
}).then(data => {
console.log(data);
})

最新文章

  1. Npoi导出Excel 实战篇(Webform)
  2. linux命令详解之挂载光驱的方法
  3. Linux下Mysql安装
  4. Opencv加载和显示图片
  5. DP编辑距离
  6. CAS单点登录配置[3]:服务器端配置
  7. ACM2096_小明A+B
  8. nodejs 简单http 文件上传demo
  9. linux命令行常用快捷键
  10. x0vncserver Fatal server error: no screens found
  11. Android 开发之错误整理java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10088 nor current process has android.permission.READ_PHONE_STATE.
  12. 浅谈MVC异常处理
  13. vmware安装FreeBSD8.3全攻略【教程】
  14. Arcgis Engine axMapControl1.get_layer(index)中index意义
  15. T SQL 将一列多行数据合并为一行
  16. tomcat 的acceptCount、acceptorThreadCount、maxConnections、maxThreads 如何确定
  17. SharePoint Framework 企业向导(十)
  18. .net core中Quartz的使用
  19. 'Project Name' was compiled with optimization
  20. python 冒泡排序的总结

热门文章

  1. Kotlin 委托(1)类委托、变量委托注意事项
  2. 通过gevent实现单线程下的多socket并发
  3. AT2164 Rabbit Exercise
  4. mysql查询某个字段并修改
  5. drf的序列化器
  6. vue前后端分离
  7. js 正则去除html代码
  8. android中的http框架,使其更加简单易用
  9. Spring Boot 数据库连接池参数
  10. [运维]Dell R710 raid配置 标签: raid运维 2017-04-15 19:35 581人阅读 评论(16)