量角器 - 如何将promises数组的结果导入另一个数组,并在其他函数中使用该数组

时间:2015-08-23 15:27:10

标签: javascript arrays angularjs protractor

我从下面的代码中获得了一系列的promise,但我发现很难将数据放到另一个数组中,以便我可以在其他函数中使用该数组。

    var AdidToCheckInDelete = [];

    var getArray = function() {

    var result = element.all(by.repeater('adId in campaign.adIds')).map(function (elem) {
                return elem.all(by.model('campaign.adIds[$index]')).getAttribute('value').then(function (text) {
                    return text ? text[0] : text;
                    });
                });

    result.then(function (elem) {
                console.log('element is' + elem);
                var array = elem;
                AdidToCheckInDelete.push(array);
                    console.log('array created with values + AdidToCheckInDelete);
                });
            console.log('Array outside the scope is' +AdidToCheckInDelete);
 //PROBLEM AdidToCheckInDelete is Empty
            };

推送数组的值并在范围内打印它们给出了数组,但是在范围外打印它会给出一个空数组。 请为我提供解决方案。提前谢谢......

1 个答案:

答案 0 :(得分:1)

您的数组为空的原因是因为Protractor正在执行 console.log()语句,甚至在 map()功能的承诺解决之前< strong> push()方法被链接。要解决此问题,请尝试在解析承诺后记录您的数组,在您的情况下,已经在推送方法数组变量之后完成。

result.then(function (elem) {
    console.log('element is' + elem);
    var array = elem;
    AdidToCheckInDelete.push(array);
    //Printing array here makes sense as map() function promise is resolved and then you are trying to print it
    console.log('array created with values + AdidToCheckInDelete);
});

或者您可以在包含push方法的函数旁边链接控制台日志记录。这是你如何做到的 -

result.then(function (elem) {
    console.log('element is' + elem);
    var array = elem;
    AdidToCheckInDelete.push(array);
})
.then(function(){
    console.log('Array outside the scope is' +AdidToCheckInDelete);
    //Your array wont be empty now
    //If you want to use your array for next operation you can do it here
});

您还可以尝试添加阻止延迟() - &gt; fulfill()机制使其等待/阻塞,直到解析了promise,参见:

- Prevent Protractor from finishing before promise has been resolved