Promise to async await when polling

若如初见. 提交于 2020-01-04 06:36:05

问题


I'm trying to convert a function that uses promise (and polling) to an async function, but I'm not really sure how it works.

I have this:

function myFunction() {
    return new Promise(resolve => {
        // stuff here ...

        var poll = setInterval(function() {
            if (condition) {
                clearInterval(poll);
                resolve("done");
            }
        }, 100);
    });
}

.. but I'm unsure what to await here:

async function myFunction() {
    // stuff here ...

    var poll = setInterval(function() {
        if (condition) {
            clearInterval(poll);
            // await what?
        }
    }, 100);
}

回答1:


setInterval does not play nice with async await. It is best to use a 'promisified' version of setTimeout that you call again on each iteration of the loop.

const myFunction = async = () => {
  let condition = false;

  while (!condition) {
    await new Promise(resolve => setTimeout(resolve, 100));
    condition = processCondition();
  }
}



回答2:


async function myFunction() {
    // stuff here ...
    var poll = await setInterval(function() {
        if (condition) {
            clearInterval(poll);
            // await what?
        }
    }, 100);
}


来源:https://stackoverflow.com/questions/57213034/promise-to-async-await-when-polling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!