promise如何控制并發(fā)請求?
第三種的方式
//省略代碼 // 計數(shù)器 var count = 0; // 全局鎖 var lock = []; var l = urls.length; // 阻塞函數(shù) Function block(){ let _resolve; return new Promise((resolve,reject)=>{ _resolve=resolve; // resolve不執(zhí)行,將其推入lock數(shù)組; lock.push(_resolve); }); } // 叫號機 function next(){ lock.length&&lock.shift()() } async function bao(){ if(count>=3){ //超過限制利用await和promise進行阻塞; await block(); } if(urls.length>0){ console.log(count); count++ await loadImg(urls.shift()); count--; next() } } for (let i = 0; i < l; i++) { bao(); }