[英]Make calls to async function to be executed sequentially in JavaScript
如何實現send
功能,以便calculate
將按順序執行,並保留調用順序?
async function calculate(value) {
return new Promise((resolve) => {
setTimeout(() => resolve(value * value), 1)
})
}
async function send(value) {
return await calculate(value)
}
calculate
的下一次調用。calculate
調用應該以完全相同的順序到達。await
結果。當調用者忽略結果時,它應該以這種方式工作(我們總是返回結果並且不關心它是否被使用)
send(2)
send(3)
以及異步調用
;(async () => {
console.log(await send(2))
console.log(await send(3))
})()
聚苯乙烯
為什么它被否決了? 對於有狀態的遠程服務來說,這是一個完全合法的用例,其中calculate
將是遠程調用。 而且您必須保留順序,因為遠程服務是有狀態的,結果取決於調用順序。
這是我設置異步隊列的方法,以便它按順序處理事物,而不管它們如何調用:
function calculate(value) {
var reject;
var resolve;
var promise = new Promise((r, rr) => {
resolve = r;
reject = rr;
})
queue.add({
value: value,
resolve: resolve,
reject: reject
});
return promise;
}
var calcluateQueue = {
list: [], // each member of list should have a value, resolve and reject property
add: function(obj) {
this.list.push(obj); // obj should have a value, resolve and reject properties
this.processNext();
},
processNext: async function() {
if (this.processing) return; // stops you from processing two objects at once
this.processing = true;
var next = this.list.unshift(); // next is the first element on the list array
if (!next) return;
try {
var result = await doSomeProcessing(next.value);
next.resolve(result);
this.processNext();
} catch(e) {
next.reject(e);
// you can do error processing here, including conditionally putting next back onto the processing queue if you want to
// or waiting for a while until you try again
this.processNext();
}
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.