Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
JavaScript queue promise resolution until async call is finished (way to improve)

I have found an interesting algorithm that I would like to know if it is really necessary or if there is a way to improve it because the code is very confusing. Essentially, the getValue method can be called at any time (it's part of library code) and it is necessary to guarantee that the call to the server is made only once. If someone need value while it's being loaded from server, the promise should wait until server response. The solution in this case is to accumulate the method calls in a queue and then, when the server call promise is resolved, execute everything accumulated.

I understand that due to the asynchrony of the language something like this is necessary, but can there be something better?

Demo code:

function getValueFromServer() {
  console.log("get value from server");
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("value");
    }, Math.floor(Math.random() * 10));
  });
}

var singObj = {
  value: "",
  working: false,
  queue: [],
  getValue: function() {
    if (!this.working && this.value !== "") {
      console.log("not working and value exists");
      return value;
    }

    return new Promise(async(resolve, reject) => {
      console.log("queue resolution...");
      this.queue.push(resolve);

      if (!this.working) {
        this.working = true;
        this.value = await getValueFromServer();
        this.working = false;
        this.queue.forEach((f) => {
          f(this.value);
        });
      }
    });
  }
}

function getValueUsage() {
  var result = Promise.allSettled([singObj.getValue(), singObj.getValue(), singObj.getValue()]);
  console.log(result);
  var result = Promise.allSettled([singObj.getValue(), singObj.getValue(), singObj.getValue()]);
  console.log(result);
}

getValueUsage();

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This can be done much simpler indeed. A promise already does hold onto its result value forever, and you can call .then() on the same promise multiple times. So all you need to do is

var singObj = {
  promise: null,
  getValue: function() {
    if (!this.promise)
      this.promise = getValueFromServer();
    return this.promise;
  }
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda