gpt4 book ai didi

javascript - 如何在异步调用中跟踪同步变量

转载 作者:行者123 更新时间:2023-11-27 22:36:15 25 4
gpt4 key购买 nike

我正在使用 Protractor 来运行 e2e 测试用例。所有 Protractor 调用都是异步调用。下面的代码是 Protractor 代码:

 gridRow.then(function (rows) {
for (var index = 0; index < rows.length; index++) {
console.log(index); -------------------- 1
rows[index].all(by.className('ui-grid-cell-contents ng-scope')).get(1).getText().then(function (text) {
console.log(index); ----------------- 2
if (text.toUpperCase().replace(/ |-/g, '') === 'BRANCHONE') {
console.log(index); -------------- 3
}
});
}
});

本例中的 rows.length = 2。 1 处的 Console.log 按预期输出 0 和 1,但 2 和 3 处的 console.log 输出为 2,因为 then 调用是异步的。由于异步调用并行运行,同时索引值更新为 2(index++)。

知道如何在异步调用中跟踪同步变量(索引)吗?

最佳答案

我通常做的是将回调函数包装在另一个函数中,以在新的作用域中捕获同步变量。为了说明这一点,您现在所拥有的实际上是:

var callback = function(text) {
// use text and index...
};
async_call(...).then(callback);

问题当然是 index 变量(由回调函数捕获)在创建回调后发生变化。由于回调函数使用闭包来捕获对该值的引用,因此它最终会看到更改后的值。

要在特定循环迭代期间捕获 index 的值,您可以创建一个新作用域,其中包含一个不会更改的新变量。基本上,您创建另一个函数并使用当前索引调用它,并且该函数的参数捕获该特定值。然后,您可以让该函数返回另一个用作回调的函数。示例代码来澄清这个可怕的描述:

function createCallback(curIndex) {
return function(text) {
// use text and curIndex...
};
}

//...

var callback = createCallback(index); // where index is the variable you are looping over
async_call(...).then(callback);

通过将 createCallback 设为匿名函数,可以将其编写得更紧凑:

var callback = (function(curIndex){
return function(text) {
// use text and curIndex...
};
})(index);
async_call(...).then(callback);

有关 JavaScript 中的闭包和函数的更多信息,请参阅 this comprehensive answer .

关于javascript - 如何在异步调用中跟踪同步变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39073018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com