简体   繁体   中英

typescript - while loop for promise

I've a large array which is split into smaller chunks. Then I make an asyncronous call on each chunk:

  myFunc(arrObjs: any[], chunkSize: number): Promise<any> {
    let result = Promise.resolve(); // To start the chain

    while(arrObjs.length) {
      // Extracting array chunk
      let chunk = arrObjs.splice(0, chunkSize);
      // Building the chain
      result = result.then(() => {
        return someAsynFunc(
          chunk
        );
      });
    }
    return result;
  }

Above my solution. I need to run async functions in order (series promise), so I build a chain of promises.

Are there any better ways to do this?

Yes, you can use the reduce pattern:

function myFunc(arrObjs: any[], chunkSize: number): Promise<any> {
    const chunks : any[] = [];
    while (arrObjs.length) {
        chunks.push(arrObjs.splice(0, chunkSize));
    }

    return chunks.reduce((p : Promise<any>, chunk : any[]) => {
        return p.then(() => someAsyncFunc(chunk));
    }, Promise.resolve());
  }

(I think I have those type annotations right; if not, hopefully you can read past it...)

Note that I've preserved your original behavior actually removing the data from the arrObjs array, but normally I wouldn't advocate changing the object passed from the caller like that.

Here's an example:

 function myFunc(arrObjs, chunkSize) { const chunks = []; while (arrObjs.length) { chunks.push(arrObjs.splice(0, chunkSize)); } return chunks.reduce((p, chunk) => { return p.then(() => someAsyncFunc(chunk)); }, Promise.resolve()); } function someAsyncFunc(chunk) { console.log("Start handling", JSON.stringify(chunk)); return new Promise(resolve => { setTimeout(() => { console.log("Done handling", JSON.stringify(chunk)); resolve(); }, 800); }); } const array = [0, 1, 2, 4, 5, 6, 7, 8, 9]; myFunc(array, 3).then(() => { console.log("Done"); }); 


Also note that the above removes all chunks from the array in advance of processing them. If you want to do it as they're processed (which creates cross-talk with anything else using that array, which could add/remove/etc.), you can do much the same thing, just without reduce :

// Cross-talky version
function myFunc(arrObjs : any[], chunkSize : number) : Promise<any> {
  return new Promise<any>(function processChunk(resolve : function) {
    const chunk : any[] = arrObjs.splice(0, chunkSize);
    if (chunk.length == 0) {
      resolve();
    } else {
      someAsyncFunc(chunk).then(() => processChunk(resolve));
    }
  });
}

 // Cross-talky version function myFunc(arrObjs, chunkSize) { return new Promise(function processChunk(resolve) { const chunk = arrObjs.splice(0, chunkSize); if (chunk.length == 0) { resolve(); } else { someAsyncFunc(chunk).then(() => processChunk(resolve)); } }); } function someAsyncFunc(chunk) { console.log("Start handling", JSON.stringify(chunk)); return new Promise(resolve => { setTimeout(() => { console.log("Done handling", JSON.stringify(chunk)); resolve(); }, 800); }); } const array = [0, 1, 2, 4, 5, 6, 7, 8, 9]; myFunc(array, 3).then(() => { console.log("Done"); }); setTimeout(() => { array.splice(2, 0, 'cross', 'talk'); }, 1000); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM