Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Promise控制并发原理 #100

Open
bojue opened this issue Sep 21, 2020 · 0 comments
Open

Promise控制并发原理 #100

bojue opened this issue Sep 21, 2020 · 0 comments

Comments

@bojue
Copy link
Owner

bojue commented Sep 21, 2020

核心原理

通过for循环遍历执行Promise,根据并发数目判断是否继续执行下一个Promise

let limitPromise = (limitNum , promiseList) =>{
    let resolveResult = [];
    let len = promiseList.length;
    let currIndex = 0;

    return new Promise((resolve) => {
        let run = () => {
            if(!promiseList.length) return;
            promiseFun(promiseList.shift())
            .then(res=> {
                resolveResult.push(res)
            })
            .catch(e => {
         
            })
            .finally(()=> {
                currIndex += 1;
                if(currIndex === limitNum) {
                    resolve(resolveResult)
                }
            })
        }

        for(let i=0;i<limitNum;i++) {
            run();
        }
    }) 

    function promiseFun(promise) {
        return new Promise((resolve, reject)=> {
            promise.then( res => resolve(res)).catch(e => reject(e))
        })
    }
}

let p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(1);
  }, 1000);
});
let p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(2);
  }, 2000);
});
let p3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(3);
  }, 3000);
});

let limt = limitPromise(2, [p1, p2, p3]);
limt.then(res => {
    console.log(res)
})

并发控制

通过截取数组分步执行

async function PromiseAll(promises,batchSize=10) {
 const result = [];
 while(promises.length > 0) {
   const data = await Promise.all(promises.splice(0,batchSize));
   result.push(...data);
 }
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant