ES6的基础知识(三)

4次阅读

共计 1885 个字符,预计需要花费 5 分钟才能阅读完成。

promise
// resolve() 会触发 then 方法第一个回调, reject() 会触发 then 方法第二个回调或 catch 方法
let p = new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
resolve(“ 成功操作 ”);
} else {
reject(“ 失败操作 ”);
}
});
});

p.then(
res => {
console.log(res);
},
err => {
console.log(err);
}
);
generator
// yield 会终止 fn() 的执行, 需要 next() 方法触发 fn() 向下执行
function* fn(x) {
yield x[0];
yield x[1];
yield x[2];
}

let res;
let t = fn([1, 2, 3]);
do {
res = t.next();
console.log(res);
} while (!res.done);

// 执行结果
// {value: 1, done: false}
// {value: 2, done: false}
// {value: 3, done: false}
// {value: undefined, done: true}
实现 promise
// Promise 的参数是一个函数 async,async() 有 resolve 和 reject 两个参数
function Promise(async) {
// 回调函数中 this 会指向 window, 需要保存才会指向 Promise 实例对象
let _this = this;
// Promise 三种状态, 分别为 pending,resolved,rejected. 状态只能从 pending 变成 resolved 或者 rejected
_this.status = “pending”;
_this.val = undefined;
// 成功回调方法集合
_this.onResolvedCallbacks = [];
// 失败回调方法集合
_this.onRejectedCallbacks = [];
// 触发 resolve() 方法异步状态改变成成功, 将会执行成功回调集合中的方法
function resolve(val) {
if (_this.status === “pending”) {
_this.status = “resolved”;
_this.val = val;
_this.onResolvedCallbacks.forEach(item => item(val));
}
}
// 触发 reject() 方法异步状态改变成失败, 将会执行失败回调集合中的方法
function reject(val) {
if (_this.status === “pending”) {
_this.status = “rejected”;
_this.val = val;
_this.onRejectedCallbacks.forEach(item => item(val));
}
}
// 异常捕获
try {
async(resolve, reject);
} catch (err) {
reject(err);
}
}
// then 方法有两个参数, 第一个异步成功后执行的函数, 第二个是异步出异常后执行的函数
Promise.prototype.then = function(resolved, rejected) {
let _this = this;
if (_this.status === “pending”) {
// 将所有 then 要执行的方法 push 到回调函数集合中, 在状态改为 resolved 执行其中的方法
_this.onResolvedCallbacks.push(resolved);
// 将所有 then 要执行的方法 push 到回调函数集合中, 在状态改为 rejected 执行其中的方法
_this.onRejectedCallbacks.push(rejected);
}
if (_this.status === “resolved”) {
resolved(_this.val);
}
if (_this.status === “rejected”) {
rejected(_this.val);
}
};
实现 generator
// 生成器
function fn(val) {
let i = 0;
return {
next() {
let done = i === val.length;
let value = val[i++];
return {
value,
done
};
}
};
}

// 迭代器
let it = fn([1, 2, 3]);
let result;
do {
result = it.next();
console.log(result);
} while (!result.done);

正文完
 0