Assign a value returned from a promise to a global

2019-08-03 05:04发布

问题:

I'm trying to read the browser memory values from Protractor and store them in a global object. To do that I'm getting the window.performance.memory object and then resolving the promise to inspect each of the memory values.

The problem is that I cannot seem to be able to assign the value to a global variable. I've tried the following code, which doesn't seem to work quite well:

 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);
};

This returns:

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

回答1:

Because console.log('Variable outside the promise: ' + HeapSizeLimit); is executed before HeapSizeLimit = memoryValues.jsHeapSizeLimit;. If it's on the line after the promise, doesn't mean the execute order is the same.



回答2:

// 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;
    });
};

In your test:

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);
};

Worth nothing: setting your variable and retrieving the value can appear to happen synchronously (outside controlFlow) or asynchronously (via the deferred executions within protractor tests).