写在后面,dataloader 代码曾经很少了,只有三百行而且一半是正文。然而我就是想写
/**
* 一个承受 ids 而后返回后果的函数 handle,* 对这个 handle 进行封装,返回一个 loader
* 每次通过调用 loader 来调用 handle
* 每接管到一个对 loader 的调用
* 就存储起来,并不立刻执行 handle
* 而是收集 loader 的参数 id,并且将多个 id 合并为 ids
* 最初在 js 执行的开端,调用一次 handle(ids) 这样
*
* @export
* @param {(id: number) => {}} handle
*/
export default function Dataloader<T>(handle: (ids: number[]) => Promise<T[]>) {const cachesMap = {};
const loader = {cacheIdsQue: [] as {id: number; resolve: Function; reject: Function}[],
load: function (id: number) {const quePromise = new Promise((resolve, reject) => {
this.cacheIdsQue.push({
id,
resolve,
reject
});
if (this.cacheIdsQue.length === 1) {this.nextTickRun();
}
})
return quePromise;
},
nextTickRun() {Promise.resolve().then(() => {if (this.cacheIdsQue.length) {
const cacheIdsQue = this.cacheIdsQue;
const results = handle(this.cacheIdsQue.map(ref => ref.id));
results.then((values) => {values.forEach((element, index) => {cacheIdsQue[index].resolve(element);
});
this.clearQue();})
}
});
},
clearQue() {this.cacheIdsQue = [];
}
}
return loader;
}
// 测试
const loader = new Dataloader((ids) => {
return Promise.resolve(ids.map(id => {return id + 'abc';}));
});
loader.load(3).then(console.log)
loader.load(1).then(console.log)
loader.load(2).then(console.log)