Created
May 7, 2019 04:31
-
-
Save JustinSDK/b4334bbf8062da2a8de9028d1fa3cb50 to your computer and use it in GitHub Desktop.
es6-iterator-promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 自行實作迭代器 | |
const vertex1 = { | |
x: 1, | |
y: 2, | |
z: 3, | |
[Symbol.iterator]() { | |
const keys = Object.keys(this); | |
let i = 0; | |
return { | |
next: () => { | |
return { | |
value: Promise.resolve(this[keys[i++]]), | |
done: keys.length === i - 1 | |
}; | |
} | |
}; | |
} | |
}; | |
for(let p of vertex1) { | |
p.then(vo => { | |
console.log(vo); | |
}); | |
} | |
// 透過產生器函式 | |
const vertex2 = { | |
x: 1, | |
y: 2, | |
z: 3, | |
[Symbol.iterator]: function* () { | |
const values = Object.values(this); | |
let i = 0; | |
for(let i = 0; i < values.length; i++) { | |
yield Promise.resolve(values[i]); | |
} | |
} | |
}; | |
for(let p of vertex2) { | |
p.then(vo => { | |
console.log(vo); | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment