【问题标题】:Webdriverio execute custom command wait for async call on the browser sideWebdriverio 在浏览器端执行自定义命令等待异步调用
【发布时间】:2017-09-09 06:17:58
【问题描述】:

我有一个问题

这是我的自定义命令

 client.addCommand('getBinaryImage', function (message) {
            var self = this;
            return self.execute(
                function downloadImageBinary(url) {
                    var err = null;
                    var result = null;

                    function toDataURL(url, callback) {
                        var xhr = new XMLHttpRequest();
                        xhr.onload = function () {
                            var reader = new FileReader();
                            reader.onloadend = function () {
                                callback(reader.result);
                            };
                            reader.readAsDataURL(xhr.response);
                        };
                        xhr.open('GET', url);
                        xhr.responseType = 'blob';
                        xhr.send();
                    }

                    toDataURL(url, function (dataUrl) {
                        alert('RESULT:' + dataUrl);
                        // Now return the result !!
                    });
                }
            );
        });

我使用它如下

  let chain = client
                        .url("https://stackoverflow")
                        .getBinaryImage("image url here")
                        .then((result) => {
                            console.log(result);
                        })

但正如您所见,脚本在浏览器端的执行是异步的。

问题是我需要按链顺序执行这个脚本同步,所以在结果没有准备好之前它不应该到达链中的then处理程序。

请建议如何实施?

【问题讨论】:

    标签: javascript node.js asynchronous webdriver webdriver-io


    【解决方案1】:

    您需要返回一个仅在您取回数据时才解决的承诺。 我使用http://bluebirdjs.com 作为promises 库,他们也有一个不错的简单示例-http://bluebirdjs.com/docs/api/new-promise.html

    使用
    return new Promise(function (resolve, reject) {

    包装您的整个函数

    当你得到结果时(你的// Now return the result !! 代码)调用resolve(dataUrl)

    【讨论】:

    • 但是我怎样才能从浏览器返回承诺,AFAIK 所有的通信都是序列化的
    • @bxfvgekd - 它是异步的,就像 node.js 代码一样。就像你调用的 XHR 函数一样,它是异步的。
    • 是的,你是对的,但是当调用execute时,它会将序列化的脚本发送到浏览器并在那里执行,当调用return语句时,它将序列化结果并将其发送回我的 node js 应用程序,因此它是一个简单的文本,仅此而已
    猜你喜欢
    • 1970-01-01
    • 2017-09-01
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2013-12-01
    • 2018-03-12
    相关资源
    最近更新 更多