async await with setInterval

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

    await expression causes async to pause until a Promise is settled

    so you can directly get the promise's result without await

    for me, I want to initiate Http request every 1s

    let intervalid 
    async function testFunction() {
        intervalid = setInterval(() => {
            // I use axios like: axios.get('/user?ID=12345').then
            new Promise(function(resolve, reject){
                resolve('something')
            }).then(res => {
                if (condition) {
                   // do something 
                } else {
                   clearInterval(intervalid)
                }    
            })  
        }, 1000)  
    }
    // you can use this function like
    testFunction()
    // or stop the setInterval in any place by 
    clearInterval(intervalid)

提交回复
热议问题