Skip to content

Signals

DigitalBrainJS edited this page Oct 17, 2021 · 1 revision

Signals

Every CPromise instance can handle "signals", emitted using emitSignal method. The method emits a signal event on each pending promise in the chain until some handler returns true as the result. This method is used internally for predefined system signals for cancellation and suspending actions.

Live demo

const CPromise= require('../lib/c-promise');

const chain= new CPromise((resolve, reject, scope)=>{
    scope.on('signal', (type, data) => {
        if (type === 'inc') { // ignore other signal types
            console.log(`Signal ${type} handled`);
            resolve(data.x + 1);
            return true; // we have accepted this signal, so we should return `true` to stop the propagation
        }
    });
}).then(
    (value)=> console.log(`Done: ${value}`),
    (err)=> console.log(`Failed: ${err}`)
)

setTimeout(() => {
    // returns true
    console.log(`Inc signal result: ${chain.emitSignal('inc', {x: 2})}`);
    // returns false because there are no handlers to catch this signal type
    console.log(`Custom signal result: ${chain.emitSignal('custom')}`); 
});

Console output:

Signal inc handled
Inc signal result: true
Custom signal result: false
Done: 3

Process finished with exit code 0

There are the following system signals (just for reference, don't use them unless you know what you are doing):

  • CPromise.SIGNAL_CANCEL
  • CPromise.SIGNAL_PAUSE
  • CPromise.SIGNAL_RESUME
Clone this wiki locally