JavaScript在while循环中等待异步功能 [英] JavaScript wait for async functions in while loop

查看:153
本文介绍了JavaScript在while循环中等待异步功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有5个职能;每个人都使用 setInterval 等待元素加载,然后在该元素可用时单击该元素,这将导致下一个网页.这些功能也发生在 while 循环内.这些功能一个接一个地执行,并且 while 循环等待所有功能完成然后再次循环,这一点非常重要.由于这些函数是异步的,因此循环将在所有函数甚至没有加载之前就运行 x 次.

I currently have 5 functions; each one uses setInterval to wait for an element to load and than clicks the element when it is available which leads to the next webpage. These functions also take place inside of a while loop. It is very important that these functions take place one after another and the while loop waits for all the functions to complete before looping again. Due to the functions being asynchronous the loop will run x times before any of the functions can even load.

我想做的事的例子:

function one () {
    var checkForItem = setInterval(function () {
        if ($('#element').length) {
            $('#element').click();
            clearInterval(checkForItem);
        }
    }, 100);
}

想象一下其中的5个功能(一个两个三个四个五个),都使用 setInterval 和以下 while 循环使用相同的格式:

Imagine 5 of these functions (one, two, three, four, five), all with the same format using setInterval and the following while loop:

var x = 0, y = 10;

while (x < y){
    one();
    two();
    three();
    four();
    five();
    x++
}

在继续循环之前,我将如何确保所有功能接连发生?

How would I go about ensuring all the functions take place one after another before having the loop continue?

注意:尽管由于函数异步,所以循环仍在函数完成之前继续进行.

Note: I have tried using promises although due to the functions being async the loop still continues before the functions complete.

推荐答案

在承诺中使用 async / await 语法:

function delay(t) {
    return new Promise(resolve => setTimeout(resolve, t));
}
async function one() {
    while (!$('#element').length) {
        await delay(100);
    }
    $('#element').click();
}

async function main() {
    for (var x = 0; x < 10; x++) {
        await one();
        await two();
        await three();
        await four();
        await five();
    }
}

这篇关于JavaScript在while循环中等待异步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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