const dataloader = function*(f, ...urls) {
for (const url of urls) {
const json = yield fetch(url, { method: "GET" }).then(res => res.json());
f(json);
}
};
but f
와 데이터를 fetch 하는 부분이 같이 가지고 있음
단일 책임 원칙 위반
const dataloader = function*(f, ...urls) {
for (const url of urls) {
const json = yield fetch(url, { method: "GET" }).then(res => res.json());
yield json
}
};
const render =function(...urls){
const iter =dataLoader(...urls);
const next =({value,done})=>{
if(!done){
if(value instanceof Promise) value.then(v=>next(iter.next(x)))
else{
console.log(value)
next iter.next()
}
}
};
next(iter.next())
}
async example
const render = async (...urls) => {
for (const url of urls) {
console.log(await await fetch(url, { method: "GET" }).json());
}
};
const dataLoader = async function*(...urls) {
for (const url of urls) {
yield await (await fetch(url, { method: "GET" })).json();
}
};
const render = async function(...urls) {
for await (const json of dataLoader(...urls)) {
console.log(json);
}
};
generator 가 generator 를 부른다.
new Array().map().forEach() 를 사용하면 . 을 사용할 때마다 새로운 Array를 생성
const urlLoader = async function*(url) {
yield await (await fetch(url, { method: "GET" })).json();
};
const dataLoader = async function*(...urls) {
for (const url of urls) yield* urlLoader(url);
};
const Url = class {
#url;
#opt;
constructor(url, opt) {
this.#url = url;
this.#opt = opt;
}
async *load() {
yield await (await fetch(this.#url, this.#opt)).json();
}
};
let url = (url, opt = { methd: "GET" }) => new Url(url, Option);