javascript - Running async function from a loop -
i'm not looking solution in particular language, want understand practices in area of running async tasks loop.
this have thought of far:
var callacc = 0; var resultarr = []; (var k = 0; k < 20; k++) { callacc ++; asyncfunction("variable") .then(function (result) { resultarr.push(result); if (callacc === resultarr.length) { // resultarr } }) .catch(function (err) { console.warn(err); }); } at point, i'm using sync variable let me proceed once have of async tasks complete. however, feels hacky , wondering if there kind of design pattern execute aync tasks loop
edit: based on proposed solutions, ended using
var promises = []; (var = 0; < 20; ++) { promises.push(asyncfunction("param")); } promise.all(promises) .then(function (result) { console.log(result); }) .catch(function (err) { console.warn(err); }); thank everyone!
instead of running async tasks within loop, can abstract away task of waiting on promises using promise.all function, take iterable of promises , create new promise return array of results in same order original list of promises of them resolve, or fail if of them fails. languages have promises have function that, , if there isn't, shouldn't hard define.
if need of promises run if of them fails, can write function too, you'd need define failed promises (discard them, return errors somehow...).
anyway, gist of best way of dealing orchestration of multiple promises define function take promises need deal , return new promise handle orchestration.
something like:
orchestratepromises(promiselist) { return new promise((resolve, reject) => { // set (let promise of promiselist) { // define how handle promises when resolve // asynchronously resolve or reject } } }
Comments
Post a Comment