K
K
komigor2021-05-10 22:54:58
Node.js
komigor, 2021-05-10 22:54:58

How to make the controller unavailable for a while?

I have a controller which, when requested, does a very long operation. And I need to block it for this time (give an error when accessing it). It should turn out something like this.

app.get(
//1) Поступил первый запрос 
//2) Длинная I/O операция 
//3) Поступил второй запрос выбрасваем ошибку(обработчик недоступен) 
//4)Длинная I/O операция закончилась 
//5) Мы снова можем принимать запросы
)

With what can this be done?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Somewhere Intech, 2021-05-11
@komigor

const Controller = function(){
  var busy = false;
  return {
    ready: () => busy === false,
    do: (data) => new Promise((resolve,reject) => {
      if (busy)
        reject("I`m busy dude!")
      busy = true;
      // +100500 code rows
      setTimeout(() => {
        busy = false;
        resolve("wow, its working fine!");
      }, 1000);
    })
  }
}

let ctrl = new Controller();

ctrl.do("something")
  .then(result => console.log("Job's done: " + result))
  
ctrl.do("fault")
  .catch(err => console.log(`Houston, we have a problem: ${err}`));
  
setTimeout(() => ctrl.do("something again").then(result => console.log("It works again: " + result)), 1100)

PS do the queue, with promises it's a few lines of code

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question