javascript - What is the best general practice to timeout a function in promise -


promisify function call timeouts

i have seen many resources provide similar examples of using promise.race timeout function call within given period of time. example of how promise.race can used in practice. here's sample code:

function dowithininterval(func, timeout) {     var promisetimeout = new promise(function (fulfill, reject) {        // rejects timeout kicks in        settimeout(reject, timeout);     });     var promisefunc = new promise(function (fulfill, reject) {         var result = func(); // function may take long finish         // fulfills when given function finishes         fulfill(result);     });      return promise.race([promisetimeout, promisefunc]); } 

the simple approach above using promise.race rejects promise timeout kicks in before func has completed. otherwise, project fulfilled once func function finishes before timeout interval.

this sounds , easy use.

however, best practice use timeout in promise?

surely, approach above can employed if want set timeout against function call using promises. operations still appear promise. however, considered practice of using timeout in promise? if not, disadvantage of using this?

i've alternative approaches, couldn't find native promise way this.

instead, external promise libraries offer timeout functionality follows:

however, promise.timeout() doesn't appear part of standard ecmascript 6 api (please correct me if i'm wrong). there recommended way handle timeouts natively es6 promises?

it depends on mean timeout.

if expect function stop, no.

if want stop waiting it, yes (quick whip in es6):

var wait = ms => new promise(resolve => settimeout(resolve, ms)); var timeout = (p, ms) => promise.race([p, wait(ms).then(() => {     throw new error("timeout after " + ms + " ms"); })]); 

var wait = ms => new promise(resolve => settimeout(resolve, ms));  var timeout = (p, ms) => promise.race([p, wait(ms).then(() => {    throw new error("timeout after " + ms + " ms");  })]);    // example:    var log = msg => div.innerhtml += "<p>" + msg + "</p>";  var failed = e => log(e.tostring() + ", line " + e.linenumber);    log("waiting 5 seconds...");  timeout(wait(5000), 2000)  .then(() => log("...done."))  .catch(failed);
<div id="div"></div>

if want cancel operation (make stop), operation comes api cancel it, , should use that, since es6 promise not control surface.

cancelable promises controversial topic in es6, of libraries mentioned offer concept.


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -

jdbc - Not able to establish database connection in eclipse -