Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

107
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda