[removed] Asynchronous method in while loop

后端 未结 8 2060
一生所求
一生所求 2020-12-15 08:28

I\'m tackling a project that requires me to use JavaScript with an API method call. I\'m a Java programmer who has never done web development before so I\'m having some trou

8条回答
  •  借酒劲吻你
    2020-12-15 09:05

    sigmasoldier's solution is correct, just wanted to share the ES6 version with async / await:

    const asyncFunction = (t) => new Promise(resolve => setTimeout(resolve, t));
    
    const getData = async (resolve, reject, count) => {
    
        console.log('waiting');
        await asyncFunction(3000);
        console.log('finshed waiting');
    
        count++;
    
        if (count < 2) {
            getData(resolve, reject, count);
        } else {
            return resolve();
        }
    }
    
    const runScript = async () => {
        await new Promise((r, j) => getData(r, j, 0));
        console.log('finished');
    };
    
    runScript();

提交回复
热议问题