D
D
dmitriyivvv2020-01-13 22:07:18
JavaScript
dmitriyivvv, 2020-01-13 22:07:18

Node.js event loop and async await?

There is the following code:

//добавляет путь файла в очередь string[];
enqueue(filePath: string): void {
    this.queue.push(filePath);

    if (!this.processing) {
      this.processing = true;
      this.ftp.connect().then(this.drain.bind(this));
    }
  }

// начинает извлекать пути из очереди, пока она не опустошится полностью
async drain(): Promise<void> {
    if (this.queue.length) {
      const filePath = this.queue.shift();
      const fileStream = await this.ftp.get(filePath);
      fileStream .on('data', chunk => this.entries.push(chunk.toString())).on('end', () => this.drain());
    } else {
      this.processing = false;
      await this.ftp.disconnect();
    }
  }

Interested in this question. Can a situation arise when the queue is empty and the drain method was called which set this.processing = false and starts waiting to disconnect from the ftp server (as far as I know, if it stumbles upon await, control is transferred further, and the event loop, respectively, does not block), and can the enqueue method be called at this moment, which will try to connect to the ftp server (because the flag this.processing === false) and resp. he has not yet managed to disconnect, but will already try to connect again, which in theory can lead to an error. Can such a situation arise or is there no event loop due to the specifics of the operation? If possible in more detail.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
abberati, 2020-01-13
@abberati

Write a function
And experiment.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question