#javascript #node.js #loops #memory #nightwatch.js
#javascript #node.js #циклы #память #nightwatch.js
Вопрос:
У меня есть функция, которая работает вне цикла. Функция ищет выпадающие элементы, сохраняет их в списке с именем elements, находит идентификатор элементов, проверяет идентификатор с помощью файла json, который описывает, какой выпадающий список выбрать, затем щелкает элемент и добавляет элемент в список используемых. Однако, когда я помещаю его в цикл while неизвестных итераций, он не может запустить функцию и застревает. Я думаю, что проблема заключается в том, как javascript выделяет память, даже после того, как я отменяю выполнение кода, мой node.js процесс продолжает использовать память до тех пор, пока в моей консоли не появится сообщение об ошибке GC. Я думаю, это может быть связано с тем, что Javascript является асинхронным, но я не знаю, как это обойти. Кто-нибудь знает, является ли это причиной, по которой он не работает? Есть ли способ заставить его работать иначе? Спасибо.
Определение функции
function DropdownInput(testList) {
client.keys(client.Keys.HOME) //Scroll to top of page
//console.log('Working here #1') ************** THE FUNCTION STOPS WORKING PAST THIS POINT ************
client.elements('xpath', '//input[@placeholder="Select"]', function (elements) { //This finds all the drop down elements on the webpage
for (const item of elements.value) {
client.elementIdAttribute(item['ELEMENT'], 'id', function (name) {
var elementId = name.value
var nextElement = JSON.stringify(testList[elementId]) //This goes through the json file and finds the input values where the json matches the webpage elements
if (nextElement !== undefined) { //This is for handling when a page element exists but is not in the json file
var inputValue = nextElement.split('"')[3] //This trims the brackets etc from the json file input
var menuCss = '#' elementId
var dropdownCss = 'li' '#' elementId '_' inputValue
client.waitForElementVisible(menuCss, 0, false, function (result) {
if (result.value) {
if (!(dropdownlist.includes(menuCss))) { //Checks that the element hasn't been clicked before
client.moveToElement(menuCss, 15, 15) //This clicks the page element that has the same id as the json the yes or no from the trimmedtext
client.execute('window.scrollBy(0,200)')
client.click(menuCss)
client.click(dropdownCss)
dropdownlist.push(menuCss)
// console.log(menuCss)
// console.log(dropdownCss)
}
}
})
}
})
}
})
}
Код с циклом
Then('the User populates all the fields', () => {
dropdownlist = []
TermsPage.getAttribute('@SubmitVersion', 'disabled', function (result) {
while (result.value === 'true') {
DropdownInput(testList)
}
})
return TermsPage.waitForElementVisible('@SubmitVersion').click('@SubmitVersion')
})
Ответ №1:
Это связано с тем, как работает очередь команд Nightwatch, это даст отличное место для ссылки https://github.com/nightwatchjs/nightwatch/wiki/Understanding-the-Command-Queue
Также всякий раз, когда у меня есть такой асинхронный код, я использую браузер.выполните ссылку: https://github.com/nightwatchjs/nightwatch/wiki/Understanding-the-Command-Queue#the-perform-command