梦魇循环内循环

时间:2017-03-17 12:25:10

标签: javascript electron nightmare

我有以下代码:

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

我正在this这个内部电子应用程序。然而,这会执行异步,我会在控制台(0,1,2,3,4,5,6,7,8,9)中立即输出,而梦魇会同时打开所有10个窗口!

如何执行以下代码同步? 我想得到以下结果:

同时反击&lt;价值(例如10)

1)counter = 0

2)nighmare工作

3)噩梦结束,反++:

1)counter = 1

2)噩梦般的工作

3)噩梦结束,反++:

e.t.c。

2 个答案:

答案 0 :(得分:0)

我认为你可以做这样的事情而不是for-loop:

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

答案 1 :(得分:0)

ES2017:您可以将异步代码包装在一个函数中,并返回一个promise(梦returns会返回promise)。

然后在for循环内调用该函数,但使用神奇的Await关键字。 :)

function DoIt(i) {
  const Nightmare = require("nightmare");
  var nightmare = Nightmare({
    openDevTools: {
      mode: "detach"
    },
    show: true
  });

  return nightmare.goto("http://google.com").end(() => {
    return true;
  });
}

(async () => {
  for (let i = 1; i <= 10; i++) {
    await DoIt(i);
  }
})();

相关问题