Exception exceptions in setInterval

Quick question if I do this:

setInterval(function() {
    try {
        riskyFunc();
    } catch(e){
        console.log(e);
    }
}, 1000);

In my head, I think that if something goes wrong in riskyFunc(), it will be caught. It's true? There are also some asynchronous calls that I know for sure inside riskyFunc().

+4
source share
3 answers

Yes, he will be caught: but only when making a callback. That is, if an riskyFuncexception is thrown, it will not fall into your example until the callback is completed in one second.

You've probably heard before that when using asynchronous methods, you should be careful with exceptions, and ordinary people do this:

try {
    setInterval(function() {
        riskyFunc();
    }, 1000);
} catch(e) {
    console.error(e);
}

, riskyFunc . , , setInterval; , setInterval , try/catch. : .

riskyFunc , . :

function riskyFunc() {
    // do some stuff
    asyncFn(function(){
        throw new Error('argh');
    }
}

try/catch setInterval. :

function riskyFunc() {
    // do some stuff
    asyncFn(function() {
        try {
            // work that may throw exception
        } catch(e) {
            console.error(e);
        }
    }
}

, " ", promises - /. , "" , :

function riskyFunc(done) {
    // do some stuff
    asyncFn(function() {
        try {
            // do some more risky work
            done(null, 'all done!');
        } catch(e) {
            done(e);
        }
    }
}

setTimeout :

setTimeout(function() {
    try {
        riskyFunc(function(err, msg) {
            // this will cover any asynchronous errors generated by
            // riskyFunc
            if(err) return console.error(err);
            console.log(msg);
        });
    } catch(e) {
        // riskyFunc threw an exception (not something it
        // invoked asynchronously)
        console.error(e);
    }
}
+8

riskyFunc

function() {
    process.nextTick(function() {
        throw "mistake";
    });
}

catch . , , , , , . (, promises . .)

+3

setInterval . - . - Promise fail(), - . jQuery Deferred, :

var promise = $.Deferred();

setInterval(function () {
    try{
       riskyFunc();
    } catch (e) {
       promise.reject(e);
    }
    promise.resolve(/* some data */);
}, 1000);

promise
    .done(function (data) { /* Handled resolve data */ })
    .fail(function (error) { /* Handle error */ });

Note that since you use setIntervalinstead setTimeout, it will be called every second if you do not clear the timeout, so if you need to call the function several times in parallel, you may need an array of promises.

+3
source

Source: https://habr.com/ru/post/1546726/


All Articles