M
M
Mark Berezovsky2020-09-22 14:45:08
Node.js
Mark Berezovsky, 2020-09-22 14:45:08

How to bypass method call chain waiting?

Let 's say I have a class that can receive and pass along a value processed by itself with a delay of 100 milliseconds:

class Gate {
    constructor(process) {
        this.process = process
        this.input = false
        this.output = false
        this.closed = false
        this.value = 0
    }

    open() {
        this.close = false
    }

    close() {
        this.close = true
    }

    // эмитируем сигнал
    emit(value) {
        if (!this.closed && this.output) this.output.update(value)
    }

    // получаем значение от сигнала
    update(value) {
        if (!this.closed) {
            // ожидание для обхода стека
            setTimeout(_ => {
                this.value = this.process(value !== undefined ? value : this.input.value)
                // отправляем дальше по цепочке
                this.emit(this.value)
            }, 100)
        }
    }

    // подключение входного объекта
    connectInput(object) {
        this.input = object
        object.output = this
    }

    // подключение выходного объекта
    connectOutput(object) {
        this.output = object
        object.input = this
    }
}

Now we try to make a clock generator based on this:
// пропускает сигнал без изменений
var a = new Gate(v => v)
// пропускает сигнал, инвертируя его
var b = new Gate(v => {
    v = v ? 0 : 1
    // вывод такта в консоль
    console.log(v)
    return v
}) // 0
// циклическая сеть
a.connectOutput(b)
b.connectOutput(a)
// запуск цикла
a.emit()

The generator works with a bang, but now there is one problem, which is what the question actually led to. When starting a loop from object "a", it will not be possible to stop it, no matter how I try to do it. Of course,
setTimeout is asynchronous and the following functions will work:
a.emit()
console.log('Ожидание старта цикла...')
// Ожидание старта цикла...
// 1
// 0
// 1...

But the thing is, I can't call methods on objects "a" and "b":
a.emit()
a.close() // Попросту не работает
b.close() // Тоже ничего

How to solve this, either a bug, or my ignorance in Node.js processes?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Yakimchuk, 2020-09-22
@soiran

It looks like there is a typo:

open() {
        this.close = false
    }

    close() {
        this.close = true
    }

Should be closed apparently

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question