我试图递归扫描mysql表并批量处理行。ids
等效于行数组,并且promise1
提取一行行并进行promise2
处理。到目前为止,这是我已经实现的。这正在按预期方式工作。如何改进它以进一步简化?
const ids=[]
for(let i=0;i<50;i++){
ids.push(i)
}
const promise1=(limit,after=-1)=>new Promise(r=>setTimeout(()=>r(ids.slice(after+1,after+limit+1)),1000))
const promise2=a=>new Promise(r=>setTimeout(()=>r(a.map(b=>b*2)),1000))
async function* promiseGen(){
let limit=10
let after=-1
while(true){
let pr1=await promise1(limit,after)
if(pr1.length==0){
break
}
yield pr1
console.log(pr1)
after=pr1[pr1.length-1]
}
}
async function processor(){
let pr1=promiseGen()
let result=[]
while(true){
let data=await pr1.next()
if(data.done){
break
}
let res=await promise2(data.value)
result.push(res)
}
return result
}
processor().then(res=>console.log(res))
最佳答案
async function processor() {
const result = [];
for await (const val of promiseGen()) {
result.push(await promise2(val))
}
return result;
}