阮大大的 ES6 入门对于我这种菜鸟来说真是太棒了!
在看 27. 异步遍历器 时,遇到的一个问题,createAsyncIterable is not defined
然后查阅的了一下,才知道异步遍历器现在是一个草案,与是冒出一个念头,这个 createAsyncIterable 函数能不能自己实现了。
j
s
c
o
d
e
js code
jscode
function createAsyncIterable(obj) {
let asyncList;
if (typeof obj === "string") asyncList = obj.split("");
else if (Array.isArray(obj)) asyncList = [...obj];
else throw new Error("Type is error");
let index = 0;
const limit = asyncList.length;
return {
[Symbol.asyncIterable]() {
return {
next() {
return new Promise((resolve, reject) => {
if (index < limit) {
resolve({ value: asyncList[index++], done: false});
} else {
resolve({ value: undefined, done: true});
}
});
}
}
}
};
}
const asyncIterable = createAsyncIterable(["a", "b"]);
const asyncIterator = asyncIterable[Symbol.asyncIterable]();
asyncIterator
.next()
.then((iterResult1) => {
console.log(iterResult1); // { value: "a", done: false }
return asyncIterator.next();
})
.then((iterResult2) => {
console.log(iterResult2); // { value: "b", done: false }
return asyncIterator.next();
})
.then((iterResult3) => { // { value: undefined, done: true }
console.log(iterResult3);
});
console.log("This is a asyncIterable");
对于我来说已经是极限了,,,开始写的时候觉得好难,但是尝试了一下发现其实很容易。。
然后,测试了一下async和await,也是ok的=。=,结果完全相同
async function f() {
const asyncIterable = createAsyncIterable(['a','b']);
const asyncIterator = asyncIterable[Symbol.asyncIterable]();
console.log(await asyncIterator.next());
console.log(await asyncIterator.next());
console.log(await asyncIterator.next());
}
f();
console.log("This is a asyncIterable");