【问题标题】:Assign a value returned from a promise to a global variable将从 promise 返回的值分配给全局变量
【发布时间】:2017-01-16 18:40:10
【问题描述】:

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

【问题讨论】:

  • 你当然可以then函数中赋值给promise之外的值,但是你不能设置它直到按时间顺序之后then 函数实际运行。
  • 谢谢@apsillers。这种解释对于理解问题所在非常有用。

标签: javascript angularjs google-chrome protractor


【解决方案1】:

因为 console.log('Variable outside the promise: ' + HeapSizeLimit);HeapSizeLimit = memoryValues.jsHeapSizeLimit; 之前执行。如果是在promise之后就行了,不代表执行顺序是一样的。

【讨论】:

  • 感谢您帮助理解问题。
【解决方案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;
    });
};

在你的测试中:

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

【讨论】:

  • 我需要它作为一个全局变量,然后我可以用它来与以前的值进行比较。
  • 我试过这个解决方案,但它返回:Expected 0 to be greater than 0.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 2017-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多