Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
Resolución de promesa de cola de JavaScript hasta que finalice la llamada asíncrona (manera de mejorar)

He encontrado un algoritmo interesante que me gustaría saber si realmente es necesario o si hay alguna forma de mejorarlo porque el código es muy confuso. Esencialmente, el método getValue se puede llamar en cualquier momento (es parte del código de la biblioteca) y es necesario garantizar que la llamada al servidor se realice una sola vez. Si alguien necesita valor mientras se carga desde el servidor, la promesa debe esperar hasta la respuesta del servidor. La solución en este caso es acumular las llamadas al método en una cola y luego, cuando se resuelva la promesa de llamada al servidor, ejecutar todo lo acumulado.

Entiendo que por la asincronía del lenguaje es necesario algo así, pero ¿puede haber algo mejor?

Código de demostración:

 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 answers
Answer question

0

Esto se puede hacer mucho más simple de hecho. Una promesa ya mantiene su valor de resultado para siempre, y puede llamar a .then() en la misma promesa varias veces. Así que todo lo que necesitas hacer es

 var singObj = { promise: null, getValue: function() { if (!this.promise) this.promise = getValueFromServer(); return this.promise; } };
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!