如何实现send
功能,以便顺序执行calculate
,并保留命令的调用?
async function calculate(value) {
return new Promise((resolve) => {
setTimeout(() => resolve(value * value), 1)
})
}
async function send(value) {
return await execute(value)
}
calculate
的下一个呼叫在上一个呼叫完成之前不应该开始。calculate
的呼叫应以完全相同的顺序到达。await
的结果应该正确返回。当调用者忽略结果时,它应该以这种方式工作(我们总是返回结果,而不管是否使用它)
send(2)
send(3)
也用于异步调用
;(async () => {
console.log(await send(2))
console.log(await send(3))
})()
这是我设置异步队列的方式,以便无论如何调用,它都会按顺序处理事物:
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();
}
}
};