猿问

promise并行串行的问题

letarr=[]
functionsendPost(text){
returnnewPromise((resolve)=>{
setTimeout(()=>{
arr.push({text,time:newDate()})
resolve(text)
},1000)
})
}
consttext1=['a1','a2','a3','a4']
consttext2=['b1','b2','b3','b4']
想要的结果如下,是一次性输出text1再每隔一秒顺序输出text2(时间格式我简略了,这不是重点),用promise的话怎么实现
arr=[{text:"a1",time:11:44:51},{text:"a2",time:11:44:51},{text:"a3",time:11:44:51},{text:"a4",time:11:44:51},{text:"b1",time:11:44:52},{text:"b2",time:11:44:53},{text:"b3",time:11:44:54},{text:"b4",time:11:44:55}]
小怪兽爱吃肉
浏览 1029回答 2
2回答

达令说

已实现~letarr=[]functionsendPost(text){returnnewPromise((resolve)=>{setTimeout(()=>{arr.push({text,time:newDate()})resolve(text)},1000)})}lettext1=['a1','a2','a3','a4']lettext2=['b1','b2','b3','b4']text1.forEach(v=>sendPost(v))constpromiseArr=text2.map(v=>()=>sendPost(v))promiseArr.reduce((prevPromise,nextPromise)=>{returnprevPromise.then(()=>nextPromise())},Promise.resolve())

慕的地6264312

没看懂你的意思,实现效果是类似的consttext1=['a1','a2','a3','a4']consttext2=['b1','b2','b3','b4']letarr=[]functionsendPost(text1,text2){returnnewPromise((resolve)=>{text1.forEach(item=>{arr.push(`${item}${newDate()}`)})resolve([arr,text2])})}sendPost(text1,text2).then(res=>{console.log(res[0])returnres[1]}).then(res=>{letcurrentTime=1000res.forEach(item=>{timer=setTimeout(()=>{console.log(`${item}${newDate()}`)},currentTime)currentTime+=1000})})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答