async await with setInterval

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

    You have a few problems:

    1. Promises may only ever resolve once, setInterval() is meant to call the callback multiple times, Promises do not support this case well.
    2. Neither setInterval(), nor the more appropriate setTimeout() return Promises, therefore, awaiting on them is pointless in this context.

    You're looking for a function that returns a Promise which resolves after some times (using setTimeout(), probably, not setInterval()).

    Luckily, creating such a function is rather trivial:

    async function delay(ms) {
      // return await for better async stack trace support in case of errors.
      return await new Promise(resolve => setTimeout(resolve, ms));
    }
    

    With this new delay function, you can implement your desired flow:

    function first(){
      console.log('first')
    }
    function second(){
      console.log('second')
    }
    let run = async ()=>{
      await delay(2000);
      first();
      await delay(2000)
      second();
    }
    run();
    

提交回复
热议问题