[removed] Asynchronous method in while loop

后端 未结 8 2054
一生所求
一生所求 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:00

    Also you may try recursion solution.

    function asyncCall(cb) {
    // Some async operation
    }
    
    function responseHandler(result) {
        if (result.error()) {
            console.error(result.error());
        } else if(result.data() && result.data().length) {
            asyncCall(responseHandler);
        }
    }
    
    asyncCall(responseHandler);
    
    0 讨论(0)
  • 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();

    0 讨论(0)
提交回复
热议问题