在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ Promise并發(fā)請求,單個請求完畢后立刻處理請求

Promise并發(fā)請求,單個請求完畢后立刻處理請求

getJSON('xxxx')
.then(function(response) {
  return Promise.all(response.results.map(getJSON));
})
.then(function(series) {
  series.forEach(addDom);
});

其中g(shù)etJSON() 是fetch請求,response.results是url的數(shù)組,addDom()是對數(shù)據(jù)的操作;
這段代碼實現(xiàn)了:1.url并發(fā)請求 2.不同請求的數(shù)據(jù)順序操作
但問題是所有請求全部加載完成后再處理數(shù)據(jù),如何實現(xiàn)當(dāng)前順序的數(shù)據(jù)加載完成后就立刻對其處理而不等待其他數(shù)據(jù)


先感謝下大家的回答!
我通過其他途徑拿到這樣一份答案,同樣利用隊列,@Xeira的方法很清晰,判斷任務(wù)是否完成很好理解;但下面這種方法promise用的讓我有點暈,不太理解
這里用Xeira的方法改了下:

(()=>{
    Promise.allInOrder = (promises, thenForEach)=>{
        let sequence = Promise.resolve();
        
        promises.forEach(function(request){
            sequence = sequence.then(function(){
              return request.then(thenForEach);
          });
        });

    };
})();

// test
(()=>{
    let timeConsumingFunc = param=>new Promise(
            (resolve)=>{
                let timeout = Math.random() * 5000;
                console.log(`task ${param} will be resolved in ${timeout}ms`);
                setTimeout(()=>{
                    console.log(`${param} resolved`);
                    resolve(param+10);
                }, timeout);
            }
        );
    Promise
        .allInOrder(
            [timeConsumingFunc(1), timeConsumingFunc(2), timeConsumingFunc(3)],
            d=>{
                return new Promise(function(resolve) {
                  console.log(d);
                resolve();
              });
            }
        )
})();
回答
編輯回答
笑忘初

Promise.race

下面有一個場景

將每一個請求想象為一個運動員,請求數(shù)據(jù)像是運動員在賽跑,第一名獎勵是可以打產(chǎn)品狗一巴掌,但是只能有一個人去打,那就看誰跑得快了~

2018年3月31日 01:50
編輯回答
我以為

all和race其實都不符合要求,all會堵到最后,而race是并發(fā)但只執(zhí)行最早結(jié)束的。

其實最簡單就是普通的一個循環(huán)執(zhí)行所有的異步,然后給每一個異步做編號,每次異步執(zhí)行完查詢該編號任務(wù)是否為當(dāng)前運行編號,不是就放入等待隊列中。每次當(dāng)前編號更新就再查詢等待隊列中有無對應(yīng)任務(wù)。

2018年3月27日 08:37
編輯回答
擱淺

寫了個例子,可以在chrome的控制臺里直接執(zhí)行

(()=>{
    Promise.allInOrder = (promises, thenForEach)=>{
        let callBackQueue = new Array(promises.length);
        let thenCallbackQueue = new Array(promises.length);

        let queueExecutor = ()=>{
            for(let i=0,l=callBackQueue.length;i<l;i++){
                if(callBackQueue[i] == void(0)){
                    // undefined means this task is not done yet
                    return;
                }else{
                    // execute callback
                    callBackQueue[i]();

                    // set this callback to null since it has been executed
                    callBackQueue[i] = ()=>{};
                }
            }
            // when reach here, it means all callbacks been executed
            Promise.all(thenCallbackQueue).then(ds=>{
                allPromiseResolver(ds);
            });
        };

        let allPromiseResolver = null, 
            allPromiseRejector = null;

        for(let i=0,l=promises.length;i<l;i++){

            promises[i].then(d=>{
                callBackQueue[i] = function(){
                    thenCallbackQueue[i] = new Promise((resolve, reject)=>{
                        let result = thenForEach(d);
                        resolve(result);
                    });
                };

                queueExecutor();
            });
        }

        return {
            all: callback=>{
                return new Promise((resolve, reject)=>{
                    allPromiseResolver = resolve;
                    allPromiseRejector = reject;
                }).then(ds=>{
                    callback(ds);
                });
            }
        }
    };
})();

// test
(()=>{
    let timeConsumingFunc = param=>new Promise(
            (resolve)=>{
                let timeout = Math.random() * 5000;
                console.log(`task ${param} will be resolved in ${timeout}ms`);
                setTimeout(()=>{
                    console.log(`${param} resolved`);
                    resolve(param+10);
                }, timeout);
            }
        );
    Promise
        .allInOrder(
            [timeConsumingFunc(1), timeConsumingFunc(2), timeConsumingFunc(3)],
            d=>{
                console.log(d);
                return d+20;
            }
        )
        .all((ds)=>{console.log(`all method called`);console.log(ds);})
})();
2017年3月22日 00:00
編輯回答
不舍棄
const container = document.querySelector('ul#container');
getJSON('xxxx').then(({results})=> {
  results.map((url, index) => {
    container.appendChild(document.createElement('li'));
    return getJSON(url).then(data => {
      container.querySelector(`li:nth-of-type(${index})`).innerHTML = addDom(data);
    })
  })
});
2017年10月26日 22:56