假设first()
,second()
和third()
函数有效,我如何在循环中异步链接它们,以便第一个解析,然后第二个在第一次解析后访问DOM,等等。
所以我可以点击类似的DOM项目并一遍又一遍地采取3项行动?
// first() pops up a list of buttons I can click
var first = setInterval(function() {
var expand = document.querySelector('a');
expand.click();
}, 1000);
// second() chooses an item and clicks it
var second = setInterval(function() {
var something = document.querySelector('a');
something.click();
}, 1000);
// third then chooses the confirm button
var third = setInterval(function() {
var area = document.querySelector('.class');
var confirm = document.querySelector('.confirm');
confirm.click();
}, 1000);
var times = 100;
var ran = 0;
while (ran < times) {
return new Promise(function(res, rej) {
first()
}).then(function() {
second()
}).then(function() {
third();
}).then(function() {
fourth();
});
ran++;
console.log(ran);
}
我认为解决问题的最简单方法是将setTimeout
包装在Promise
中,然后使用async
/ await
。这样您就可以使用已经设置的相同控制流程。
你应该使用setTimeout
而不是setInterval
。 setInterval
会按照设定的时间间隔定期运行,但是你的while
循环已经多次运行你的代码所以你应该使用setTimeout
而不是只运行一次回调。
为了简单起见,我会将setTimeout
包裹在Promise
中,这样你就可以使用async
和await
。
async
是一个修改器,放在函数上,允许你使用关键字await
。 await
所做的是解开承诺并在运行下一段代码之前等待它们解决。它允许您使用简单的同步控制流,即使代码实际上是异步的。
我做的是创建一个async
函数main
(你可以称之为你想要的任何东西)await
s包裹的setTimeout
函数。现在该函数将等到时间结束,然后运行下一段代码。
希望有所帮助!
关于浏览器兼容性的注意事项:Async和await来自最新的javascript标准,因此它不适用于IE。 qazxsw poi
来自你的评论:
谢谢!同样好奇,对我来说最好的解决方案是能够使用yield来逐步执行这些,所以我可以调用main()。next()。你知道如何将它作为具有相同时间承诺的发电机构造吗?非常喜欢这方面的帮助
我不认为这是你想要的,但它满足你的要求。也许我不得不考虑更多......
无论如何,function time(milliseconds) {
return new Promise(resolve => setTimeout(() => resolve(), milliseconds));
}
function first () {
// const expand = document.querySelector('a');
// expand.click();
console.log('first ran');
}
function second() {
// const something = document.querySelector('a');
// something.click();
console.log('second ran');
}
function third() {
// const area = document.querySelector('.class');
// const confirm = document.querySelector('.confirm');
// confirm.click();
console.log('third ran');
}
async function main() {
const times = 100;
let ran = 0;
while (ran < times) {
first();
await time(1000);
second();
await time(1000);
third();
await time(1000);
ran++;
console.log(ran);
}
}
main();
现在是一个返回承诺的函数,在run
函数中,make
s承诺yield
返回。所以现在在另一个异步功能你可以run
他们的await
s。
同样,我不认为这是你想要的,但如果你澄清你的意图,我可以给你另一个建议。
value