承诺在轮询时异步等待 [英] Promise to async await when polling

查看:86
本文介绍了承诺在轮询时异步等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将使用promise(和轮询)的函数转换为异步函数,但我不确定该如何工作.

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.

我有这个:

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

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

..但是我不确定在这里await是什么

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

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

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

推荐答案

setInterval在异步等待中表现不佳.最好使用在循环的每次迭代中再次调用的setTimeout的承诺版本".

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();
  }
}

这篇关于承诺在轮询时异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆