链接承诺在webdriver.io中的while循环

Man*_*ech 2 javascript selenium promise es6-promise webdriver-io

我想通过捕获视口大小的图块来获取完整网页的屏幕截图.这几乎已经完成,但我对承诺很新,我正在寻找正确的方法.

这是我的代码.问题是调用client.execute(...).然后(...)不会在循环迭代之间等待它自己.并且最后的"结束"既不等待之前的'那么',这就是它被评论出来的原因.

...
var client = webdriverio.remote(options);
...
client    
  ...
  .then(function() {

    var yTile = 0;
    var heightCaptured = 0;

    while(heightCaptured < documentSize.height) {
      var tileFile  = 'screenshot-' + yTile + '.png';

      client
      .execute(function(heightCaptured) {
        window.scrollTo(0, heightCaptured);
      }, heightCaptured)
      .then(function() {
        console.log('captured: ' + tileFile);
        client.saveScreenshot('./' + tileFile);

        return client;
      });

      heightCaptured += viewportSize.height;
      yTile++;
    }

  })
  //.client.end()
  ;
Run Code Online (Sandbox Code Playgroud)

在这种情况下使用promises的正确方法是什么?

谢谢.

jfr*_*d00 5

您不能使用while外观链接不确定数量的异步操作,因为while循环将立即运行完成,但您需要在每次异步执行后进行循环决策.

相反,您可以创建一个内部函数next(),它返回一个promise并重复调用它,将每个函数链接到前一个直到完成并在循环内决定是否next()通过将其返回到先前的.then()处理程序来链接另一个调用,或者您可以通过返回常规值(不是承诺).

...
var client = webdriverio.remote(options);
...
client
    ...
    .then(function () {
        var yTile = 0;
        var heightCaptured = 0;

        function next() {
            if (heightCaptured < documentSize.height) {
                var tileFile = 'screenshot-' + yTile + '.png';

                // return promise to chain it automatically to prior promise
                return client.execute(function (heightCaptured) {
                    window.scrollTo(0, heightCaptured);
                }, heightCaptured).then(function () {
                    console.log('captured: ' + tileFile);

                    // increment state variables
                    heightCaptured += viewportSize.height;
                    yTile++;

                    // return this promise to so it is also chained properly
                    // when this is done, call next again in the .then() handler
                    return client.saveScreenshot('./' + tileFile).then(next);
                });

            } else {
                // Done now, end the promise chain by returning a final value
                // Might also consider returning yTile so the caller knows
                // how many screen shots were saved
                return client;
            }
        }
        // start the loop
        return next();
    }).then(function () {
        // done here
    }, function (err) {
        // error here
    });
Run Code Online (Sandbox Code Playgroud)

作为参考,如果您在.then()处理程序中并且从.then()处理程序返回一个promise ,那么该promise将链接到前一个promise.如果您返回一个值,那么promise链就在那里结束,并返回值作为整个链的最终解析值.

所以,在这个例子中,因为next()返回一个promise,你可以return next();.then()处理程序中重复调用,并将所有截图链接在一起成为一个顺序链,直到你最终只返回一个值,而不是一个promise,这将结束链.