JavaScript 異步轉(zhuǎn)同步(偽)
? ? ??

?????????眾所周知,js成于異步,異步對(duì)于ajax,http網(wǎng)絡(luò)請(qǐng)求很重要.?但是缺點(diǎn)也很明顯,主要是不好看,可讀性差,解決方法就是用promise,但是可讀性還是不強(qiáng),所以我封裝了一個(gè)class,自我感覺良好,大家看看,提提意見(小白輕噴)。


class?SyncTask {
? ? constructor() {
? ? ? ? this.ls = []
? ? ? ? this.i?= 0
? ? }
? ? add(fun) {
????????//異步函數(shù)按書寫順序加到數(shù)組里
? ? ? ? this.ls.push(async () => {
? ? ? ? ? ? //因?yàn)槭呛瘮?shù),添加到數(shù)組時(shí)沒調(diào)用,所以不執(zhí)行
????????????//this.start()調(diào)用this.ls[0]()數(shù)組第0個(gè)異步函數(shù)后才執(zhí)行
? ? ? ? ? ? await new Promise(fun)
? ? ? ? ? ? //因?yàn)橛昧薬sync,await,所以這里是‘同步’的
????????????//先Promise(fun)成功后再if
? ? ? ? ?????if (this.i + 1 < this.ls.length) {
????????????????// 添加的時(shí)候this.i不會(huì)變,調(diào)用this.ls[0]()數(shù)組第0個(gè)異步函數(shù)執(zhí)行時(shí)才加加
? ? ? ? ? ? ? ? this.i++
?????????????//執(zhí)行第1個(gè)異步函數(shù),接下來(lái)就是一樣的循環(huán)了,執(zhí)行在數(shù)組索引的異步函數(shù)
???????????? //然后執(zhí)行下一個(gè)在數(shù)組索引的異步函數(shù)
? ? ? ? ? ? ? ? this.ls[this.i]()
? ? ? ? ? ? }
? ? ? ? })
? ? }
? ? start() {
? ? ? ? this.ls[0]()
? ? }
}

/*
使用方法
先new?這個(gè)類
var synctask = new SyncTask()
異步函數(shù)會(huì)按書寫順序執(zhí)行
? ? synctask.add(resolve => {? ?先執(zhí)行
? ? ? ? 異步函數(shù)()=>{
? ? ? ? ? ? resolve();這個(gè)要加到異步函數(shù)里。
? ? ? ? }
? ? });
? ? synctask.add(resolve => {? ?后執(zhí)行
? ? ? ? 異步函數(shù)()=>{
? ? ? ? ? ? resolve();
? ? ? ? }
? ? });
synctask.start()? ?這個(gè)是開始的函數(shù),要放到最后
*/

大家有沒覺得好用,三連一下,我會(huì)更新其他我總結(jié)的js小技巧。? ?
???????????????????????????????????????????????????????????????????????????純?cè)瓌?chuàng),如有雷同,純屬巧了不是