考虑以下异步函数,它执行一些相对繁重的计算(在本例中只是睡眠):
null
async function heavyFunc(content)
{
console.log(`Starting ${content}`);
// Sleeping 2 seconds
await new Promise(resolve => setTimeout(resolve, 2000));
console.log(content + " ENDED!");
}
heavyFunc('call 1');
heavyFunc('call 2');
heavyFunc('call 3');
null
执行此代码时,您将看到所有三条消息Call 1 Ended!
,Call 2 Ended!
和Call 3 Ended!
。
如何“停止”前两个函数调用,只完成最后一个?
因为一旦async
函数调用完成,就没有办法停止它们,所以我们必须实现某种程度上的“ID”系统,并且只完成最后一次调用的异步计算。
这里有一个简单的例子:
null
let asyncId = 0;
async function heavyFunc(content)
{
asyncId++;
let id = asyncId;
console.log(`Starting ${content}`);
// Waiting 2 seconds (these are your heavy calculations)
await new Promise(resolve => setTimeout(resolve, 2000));
// If you want you can stop further calculations right here to prevent further resource usage
if (id !== asyncId)
{
console.log(content + " ABORTED!");
return;
}
// Waiting 2 more seconds (these are your further heavy calculations)
await new Promise(resolve => setTimeout(resolve, 2000));
if (id === asyncId)
{
// This is the last call!
asyncId = 0;
console.log(content + " ENDED!");
}
}
heavyFunc('call 1');
heavyFunc('call 2');
heavyFunc('call 3');