我有以下代码:
for(var i = 0; i < 10; i ++){
DoIt();
console.log(i);
}
function DoIt(){
var nightmare = Nightmare({
electronPath: require('./node_modules/electron'),
openDevTools:{
mode: 'detach'
},
show: true
});
nightmare
.goto('http://google.com')
.end(()=>{
return true;
})
}
我正在 Electron 应用程序中使用它。然而,这会执行异步,我会立即在控制台中输出(0, 1,2,3,4,5,6,7,8,9),并且 Nightmare 会同时打开所有 10 个窗口!
如何同步执行以下代码? 我想得到以下结果:
当计数器 < 值(例如 10)时执行操作
1) 计数器 = 0
2) Nightmare 般的工作
3) Nightmare 结束,counter++
<小时/>1) 计数器 = 1
2) Nightmare 般的工作
3) Nightmare 结束,counter++
等等
最佳答案
我认为你可以做这样的事情或者for循环:
(function iteration(i) {
if (i < 10) {
DoIt(i).then(() => iteration(i + 1))
}
})(0)
为此请确保 DoIt
返回 Promise:
function DoIt(index) {
var nightmare = Nightmare({
electronPath: require('./node_modules/electron'),
openDevTools: {
mode: 'detach'
},
show: true
});
return nightmare
.goto('http://google.com')
.end(() => {
return true;
})
}
关于javascript - Nightmare 在循环内迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42857500/