[英]How to access a variable which is updated inside the function in outer scope in Cypress/Javascript?
Here is the problem statement.这是问题陈述。 I am trying to find all items on a webpage and find the item with the minimum price using Cypress.
我正在尝试查找网页上的所有商品,并使用赛普拉斯找到价格最低的商品。 The problem is, as long as I am inside the inner function, minPrice is correct.
问题是,只要我在 function 内部,minPrice 是正确的。 However when I try to print minPrice in the outer function, minPrice again gets assigned to it outer scope value.
但是,当我尝试在外部 function 中打印 minPrice 时,minPrice 再次被分配给外部 scope 值。 I am fairly new to JS, so looks like I am missing some basic JS concept here.
我对 JS 相当陌生,所以看起来我在这里缺少一些基本的 JS 概念。 I tried a lot of things like variable scoping, async/await (which cypress claims it doesnt need), but no success.
我尝试了很多东西,比如变量作用域、异步/等待(赛普拉斯声称它不需要),但没有成功。 Please help!
请帮忙!
Below is the code.下面是代码。
getMinPrice(){
//Initialize to a very big number
var minPrice = 10000;
cy.get('.btn.btn-primary').each(function ($el, index,$list) {
//For each element, do some parsing to get the price for the item
var textToParse = $el.attr('onclick');
var price = textToParse.slice(-4,-1);
price = parseInt(price,10);
//compare price with current MinPrice
if (price < minPrice)
minPrice = price;
});
cy.log(minPrice); // Logs 10000 which is not what I am expecting
}
It is because JS works asynchronously your log statement is running before the value of minPrice
is updated.这是因为 JS 异步工作,您的日志语句在
minPrice
的值更新之前运行。 To make sure that the log has the updated minprice, we can use then
to make sure the log statement is run only after each has finished executing.为了确保日志具有更新的 minprice,我们可以使用
then
来确保日志语句仅在每个语句完成执行后才运行。
cy.get('.btn.btn-primary')
.each(function ($el, index, $list) {
//For each element, do some parsing to get the price for the item
var textToParse = $el.attr('onclick')
var price = textToParse.slice(-4, -1)
price = parseInt(price, 10)
//compare price with current MinPrice
if (price < minPrice) minPrice = price
})
.then(() => {
cy.log(minPrice) //should have the updated value
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.