async await with setInterval

后端 未结 4 1017
广开言路
广开言路 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:02

    setInterval doesn't play well with promises because it triggers a callback multiple times, while promise resolves once.

    It seems that it's setTimeout that fits the case. It should be promisified in order to be used with async..await:

    async () => {
      await new Promise(resolve => setTimeout(() => resolve(first()), 2000));
      await new Promise(resolve => setTimeout(() => resolve(second()), 2000));
    }
    

提交回复
热议问题