繁体   English   中英

JavaScript 队列承诺解析,直到异步调用完成(改进方法)

[英]JavaScript queue promise resolution until async call is finished (way to improve)

我发现了一个有趣的算法,我想知道它是否真的有必要,或者是否有办法改进它,因为代码非常混乱。 本质上,getValue 方法可以随时调用(它是库代码的一部分),并且必须保证对服务器的调用只进行一次。 如果有人在从服务器加载时需要值,承诺应该等到服务器响应。 这种情况下的解决方案是在队列中累积方法调用,然后,当服务器调用承诺解决时,执行累积的所有内容。

我知道由于语言的异步性,这样的事情是必要的,但还有更好的吗?

演示代码:

 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();

这确实可以更简单地完成。 一个承诺已经永远保持了它的结果值,你可以在同一个承诺上多次调用.then() 所以你需要做的就是

var singObj = {
  promise: null,
  getValue: function() {
    if (!this.promise)
      this.promise = getValueFromServer();
    return this.promise;
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM