将promise返回的值分配给全局变量

时间:2016-09-08 18:09:24

标签: javascript angularjs google-chrome protractor

我正在尝试从Protractor读取浏览器内存值并将它们存储在全局对象中。为此,我将获取window.performance.memory对象,然后解析检查每个内存值的承诺。

问题是我似乎无法将值分配给全局变量。我尝试过以下代码,但似乎效果不好:

 this.measureMemory = function () {

    var HeapSizeLimit;

    browser.driver.executeScript(function () {
        return window.performance.memory;
    }).then(function (memoryValues) {
        HeapSizeLimit = memoryValues.jsHeapSizeLimit;
        console.log('Variable within the promise: ' + HeapSizeLimit);
    });
    console.log('Variable outside the promise: ' + HeapSizeLimit);
};

返回:

   Variable outside the promise: undefined
   Variable within the promise: 750780416

2 个答案:

答案 0 :(得分:4)

由于 console.log('Variable outside the promise: ' + HeapSizeLimit);HeapSizeLimit = memoryValues.jsHeapSizeLimit;之前执行。如果它在承诺之后的行上,并不意味着执行顺序是相同的。

答案 1 :(得分:1)

// a variable to hold a value
var heapSize;

// a promise that will assign a value to the variable
// within the context of the protractor controlFlow
var measureMemory = function() {
    browser.controlFlow().execute(function() {
        browser.driver.executeScript(function() {
            heapSize = window.performance.memory.jsHeapSizeLimit;
        });
    });
};

// a promise that will retrieve the value of the variable
// within the context of the controlFlow
var getStoredHeapSize = function() {
    return browser.controlFlow().execute(function() {
        return heapSize;
    });
};

在你的测试中:

it('should measure the memory and use the value', function() {
    // variable is not yet defined
    expect(heapSize).toBe(undefined);
    // this is deferred
    expect(getStoredHeapSize).toBe(0);

    // assign the variable outside the controlFlow
    heapSize = 0;
    expect(heapSize).toBe(0);
    expect(getStoredHeapSize).toBe(0);

    // assign the variable within the controlFlow
    measureMemory();

    // this executes immediately
    expect(heapSize).toBe(0);
    // this is deferred
    expect(getStoredHeapSize).toBeGreaterThan(0);
};

值得一无所知:设置变量并检索值可能看似同步发生(在controlFlow之外)或异步发生(通过量角器测试中的延迟执行)。