0

in my real scenario I need to stop a process that is running in a loop when a stop signal comes from a websocket.

with a design I use now I do something like this:

async function process() {
    Promise.all([
        detonator(),
        engine(),
    ]).catch(e => {
       if (e.message === 'detonated')
           console.log('it works');
       // but it's not caught at all
    })
}

async function detonator() {
    setTimeout(() => {
        console.log('throwing e');
        throw new Error('detonated');
    }, 1500);
}

async function engine() {
    while (true) {
        await wait(500);
    }
}

async function wait(ms) {
    return new Promise(resolve => {
        setTimeout(resolve, ms);
    });
}

process();

so as you can see I want to halt the engine method in the process from a remote when I throw an exception in that remote -> that would be mine message received from ws. however I need to catch that exception in that catch block in process method..which is not happening.

I assume I just need to .bind() contexts properly, but idk, I have forgot some js magic.

Please avoid commenting when you don't understand me.

appreciated

greengold
  • 1,184
  • 3
  • 18
  • 43
  • Your `process` function should not be `async` if you don't use `await` or plan to return a promise from it. – Bergi Jun 13 '20 at 15:43
  • Your detonator is throwing an exception from the `setTimeout` callback, where it cannot be caught by anything. You need to reject a promise instead, e.g. by throwing an exception inside the `async function` itself or by calling `reject` when constructing a `new Promise` around the `setTimeout`. – Bergi Jun 13 '20 at 15:48
  • as I say, this is not real word. that's why there's async even it's not asynchronous. saying this is not real word you don't need to link me how to catch exceptions from setTimeout -> that's just simulation. so I still don't know how to catch that exception from timeout -> which is not real case and you bother to close a question and link stuff. should have read a line before last one – greengold Jun 13 '20 at 16:16
  • Then what is your real code? Please [edit] your question to include it if you need more specific help. In general, there is no way to catch exceptions from asynchronous non-promise code, so you'll need to fix that code to not throw exceptions and reject promises instead. See all the linked questions for how to do that (and yes, in those `setTimeout` is not real code either but just an example). – Bergi Jun 13 '20 at 16:31
  • real code's too complicated to be readable here. but the same principle: try-catch around promise block in which engine can throw exceptions handled in promise's catch. thing is I need to be able to throw such an exception from another place and make it behave like its thrown inside promise - like it would be from engine. so that's why I say might be question ob binding contexts. but nevermind will try with rejections – greengold Jun 13 '20 at 17:04

0 Answers0