将承诺返回的值赋给全局变量



我正在尝试从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

因为console.log('Variable outside the promise: ' + HeapSizeLimit);HeapSizeLimit = memoryValues.jsHeapSizeLimit;之前执行。

// 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之外)或异步发生(通过量角器测试中的延迟执行)。

最新更新