浣跨敤Promise骞跺彂闄愬埗
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了浣跨敤Promise骞跺彂闄愬埗相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/%e6%80%9d%e8%b7%af' title='鎬濊矾'>鎬濊矾
闄愬埗 ISE var 閫昏緫 ace 澶勭悊鑳屾櫙
鎴戜滑鍦ㄩ渶瑕佷繚璇佷唬鐮佸湪澶氫釜寮傛澶勭悊涔嬪悗鎵ц,鎴戜滑閫氬父浼氫娇鐢?/p>
Promise.all(promises: []).then(fun: function);
Promise.all鍙互淇濊瘉锛宲romises鏁扮粍涓墍鏈塸romise瀵硅薄閮借揪鍒皉esolve鐘舵€侊紝鎵嶆墽琛宼hen鍥炶皟
閭d箞浼氬嚭鐜扮殑鎯呭喌鏄紝浣犲湪鐬棿鍙戝嚭鍑犲崄涓噃ttp璇锋眰锛坱cp杩炴帴鏁颁笉瓒冲彲鑳介€犳垚绛夊緟锛夛紝鎴栬€呭爢绉簡鏃犳暟璋冪敤鏍堝鑷村唴瀛樻孩鍑?
杩欎釜鏃跺€欓渶瑕佹垜浠HTTP鐨勮繛鎺ユ暟鍋氶檺鍒躲€?/p>
鍐呭
//promise骞跺彂闄愬埗
class PromisePool {
constructor(max, fn) {
this.max = max; //鏈€澶у苟鍙戦噺
this.fn = fn; //鑷畾涔夌殑璇锋眰鍑芥暟
this.pool = []; //骞跺彂姹? this.urls = []; //鍓╀綑鐨勮姹傚湴鍧€
}
start(urls) {
this.urls = urls; //鍏堝惊鐜妸骞跺彂姹犲婊? while (this.pool.length < this.max) {
let url = this.urls.shift();
this.setTask(url);
}
//鍒╃敤Promise.race鏂规硶鏉ヨ幏寰楀苟鍙戞睜涓煇浠诲姟瀹屾垚鐨勪俊鍙? let race = Promise.race(this.pool);
return this.run(race);
}
run(race) {
race
.then(res => {
//姣忓綋骞跺彂姹犺窇瀹屼竴涓换鍔★紝灏卞啀濉炲叆涓€涓换鍔? let url = this.urls.shift();
this.setTask(url);
return this.run(Promise.race(this.pool));
})
}
setTask(url) {
if (!url) return
let task = this.fn(url);
this.pool.push(task); //灏嗚浠诲姟鎺ㄥ叆pool骞跺彂姹犱腑
console.log(`x1B[43m ${url} 寮€濮嬶紝褰撳墠骞跺彂鏁帮細${this.pool.length}`)
task.then(res => {
//璇锋眰缁撴潫鍚庡皢璇romise浠诲姟浠庡苟鍙戞睜涓Щ闄? this.pool.splice(this.pool.indexOf(task), 1);
console.log(`x1B[43m ${url} 缁撴潫锛屽綋鍓嶅苟鍙戞暟锛?{this.pool.length}`);
})
}
}
//test
const URLS = [
鈥榖ytedance.com鈥?
鈥榯encent.com鈥?
鈥榓libaba.com鈥?
鈥榤icrosoft.com鈥?
鈥榓pple.com鈥?
鈥榟ulu.com鈥?
鈥榓mazon.com鈥?]
//鑷畾涔夎姹傚嚱鏁?var requestFn = url => {
return new Promise(resolve => {
setTimeout(() => {
resolve(`浠诲姟${url}瀹屾垚`)
}, 1000)
}).then(res => {
console.log(鈥樺閮ㄩ€昏緫鈥? res);
})
}
const pool = new PromisePool(5, requestFn); //骞跺彂鏁颁负5
pool.start(URLS)
浠庝笂闈㈠彲浠ョ湅鍑猴紝鎬濊矾濡備笅锛氬畾涔変竴涓?PromisePool 瀵硅薄锛屽垵濮嬪寲涓€涓?pool 浣滀负骞跺彂姹狅紝鐒跺悗鍏堝惊鐜妸骞跺彂姹犲婊★紝涓嶆柇鍦拌皟鐢?setTask 鐒跺悗閫氳繃鑷繁鑷畾涔夌殑浠诲姟鍑芥暟(浠诲姟鍑芥暟鍙互鏄綉缁滆姹傚皝瑁呯殑 promise 瀵硅薄锛屾垨鑰呮槸鍏朵粬鐨?锛岃€屼笖姣忎釜浠诲姟鏄竴涓狿romise瀵硅薄鍖呰鐨勶紝鎵ц瀹屽氨 pop 鍑鸿繛鎺ユ睜锛?浠诲姟push 杩涘苟鍙戞睜 pool 涓€?/p>
//鍒╃敤Promise.race鏂规硶鏉ヨ幏寰楀苟鍙戞睜涓煇浠诲姟瀹屾垚鐨勪俊鍙?let race = Promise.race(this.pool);
return this.run(race);
run(race) {
race
.then(res => {
//姣忓綋骞跺彂姹犺窇瀹屼竴涓换鍔★紝灏卞啀濉炲叆涓€涓换鍔? let url = this.urls.shift();
this.setTask(url);
return this.run(Promise.race(this.pool));
})
}
杩欎釜鍦版柟灏辨槸涓嶆柇閫氳繃閫掑綊鐨勬柟寮忥紝姣忓綋骞跺彂姹犺窇瀹屼竴涓换鍔★紝灏卞啀濉炲叆涓€涓换鍔?/p>
鍏朵粬
npm涓湁寰堝瀹炵幇杩欎釜鍔熻兘鐨勭涓夋柟鍖咃紝姣斿async-pool銆乪s6-promise-pool銆乸-limit锛屼篃鍙互鐩存帴鎷挎潵鐢?/p>
以上是关于浣跨敤Promise骞跺彂闄愬埗的主要内容,如果未能解决你的问题,请参考以下文章
RxJava zip鎿嶄綔绗﹀湪Android涓殑瀹為檯浣跨敤鍦烘櫙