问题描述
function first(){
console.log('first')
}
function second(){
console.log('second')
}
let interval = async ()=>{
await setInterval(first,2000)
await setInterval(second,2000)
}
interval();
想象一下我上面有这段代码.
Imagine that I have this code above.
当我运行它时,first()
和second()
会被同时调用;如何在first)()
返回一些数据后调用second()
,例如,如果first()
完成,则只有调用second()
?
When I run it, first()
and second()
will be called at the same time; how do I call second()
after first)()
returns some data, for example, if first()
is done, only then call second()
?
因为我的代码中的 first()
将处理大量数据,如果这两个函数同时调用,服务器将很难.
Because first()
in my code will be working with a big amount of data and if this 2 functions will be calling at the same time, it will be hard for the server.
每次当first()
返回一些数据时,我如何调用second()
?
How do I call second()
each time when first()
will return some data?
推荐答案
如上所述,setInterval
不能很好地与 Promise 如果你不阻止它.如果您清除了间隔,您可以像这样使用它:
As mentioned above setInterval
does not play well with promises if you do not stop it. In case you clear the interval you can use it like:
async function waitUntil(condition) {
return await new Promise(resolve => {
const interval = setInterval(() => {
if (condition) {
resolve('foo');
clearInterval(interval);
};
}, 1000);
});
}
以后你可以像这样使用
const bar = waitUntil(someConditionHere)
这篇关于使用 setInterval 异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!