如何在 Cypress/Javascript 的外部范围内访问在函数内部更新的变量?

How to access a variable which is updated inside the function in outer scope in Cypress/Javascript?

这里是问题陈述。我正在尝试查找网页上的所有商品,并使用 Cypress 查找价格最低的商品。问题是,只要我在内部函数中,minPrice 就是正确的。但是,当我尝试在外部函数中打印 minPrice 时,minPrice 再次被分配给它外部范围值。我是 JS 的新手,所以看起来我在这里缺少一些基本的 JS 概念。我尝试了很多东西,比如变量范围,async/await(赛普拉斯声称它不需要),但没有成功。请帮忙!

下面是代码。

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
}

这是因为 JS 是异步工作的,你的日志语句是 运行ning 在更新 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
  })