[英]Assign a value returned from a promise to a global variable
我正在嘗試從量角器讀取瀏覽器內存值,並將其存儲在全局對象中。 為此,我要獲取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外部)或異步發生(通過量角器測試中的延遲執行)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.