我發現了一個有趣的演算法,我想知道它是否真的有必要,或者是否有辦法改進它,因為代碼非常混亂。本質上,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();
uj5u.com熱心網友回復:
這確實可以更簡單地完成。一個承諾已經永遠保持了它的結果值,你可以.then()多次呼叫同一個承諾。所以你需要做的就是
var singObj = {
promise: null,
getValue: function() {
if (!this.promise)
this.promise = getValueFromServer();
return this.promise;
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/352327.html
標籤:javascript 异步
上一篇:異步和等待實作回傳失敗
下一篇:如何撰寫異步函式
