javascript - Ability to abort asynchronous call -
javascript - Ability to abort asynchronous call -
i'm using babeljs es7 style async/await methods. have main script phone call async method on array of objects homecoming promises. utilize promise.all() wait of return, however, these tasks take long time , if exceed threshold abort of them, , task handle in appropriate way.
is there anyway accomplish such thing? way can think of spawning process work of calling these methods , waiting them resolve, , if time limit reach, can kill process , whatever handling needs.
update: clarification these methods main script waiting on... might doing long series of operations (calling external systems, streaming files somewhere, etc) , not performing 1 single action canceled independently.
update #2: untested semi-psuedo code
class foo1 { async dosomething() { // phone call external scheme // re-create files // set files somewhere else (s3) } } class foo2 { async dosomething() { // long computations // update systems } } class foohandler { constructor() { this.foolist = []; } async start() { await promise.all(this.foolist.map(async (foo) => { homecoming await foo.dosomething(); })); } } allow handler = new foohandler(); handler.foolist.push(new foo1()); handler.foolist.push(new foo2()); // if phone call takes long because of slow connections, errors, whatever, // abort start(), handle in whatever meaningful way, , go on on. await handler.start();
native es6 promises not back upwards cancellation directly. there talks time in many places it's not there yet.
since native promises don't back upwards , async/await works on promises, there no built in easy way abort it. 1 mutual approach utilize token when creating action returning promise.
let's you've promisified xhr get:
// simplification function ajax(url){ homecoming new promise((resolve, reject) => { allow xhr = new xmlhttprequest; xhr.open("get", url); xhr.onload = () => resolve(xhr.responsetext); xhr.onerror = reject; xhr.send(); }); }
now want utilize it:
async function foo(){ allow result = await ajax("/myapi"); allow result2 = await ajax("/myapi2?token=" + result); }
now, let's want cancel ajax in cases, can pass token such:
function ajax(url, token = {}){ homecoming new promise((resolve, reject) => { allow xhr = new xmlhttprequest; xhr.open("get", url); object(token).cancel = () => { xhr.abort(), reject(); }; xhr.onload = () => resolve(xhr.responsetext); xhr.onerror = reject; xhr.send(); }); }
this allow do:
async function foo(){ allow token = {}; allow req = ajax("/myapi", token); // note no await // let's want abort request since don't // need info token.cancel(); // abort token }
this approach needs work work chaining, luckily es6 syntax not big of deal. luck , happy coding.
javascript node.js asynchronous babeljs ecmascript-7
Comments
Post a Comment