async await with setInterval

后端 未结 4 1035
广开言路
广开言路 2020-12-10 02:48
function first(){
  console.log(\'first\')
}
function second(){
  console.log(\'second\')
}
let interval = async ()=>{
  await setInterval(first,2000)
  await set         


        
4条回答
  •  旧巷少年郎
    2020-12-10 03:10

    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);
      });
    }
    

    Later you can use it like

    const bar = waitUntil(someConditionHere)
    

提交回复
热议问题