gpt4 book ai didi

javascript - 并行同步 XMLHttpRequests 只回调一次

转载 作者:行者123 更新时间:2023-11-30 00:28:45 26 4
gpt4 key购买 nike

我正在异步地并行发出两个 API 调用,这样我就不会锁定浏览器,而且我只收到一个回调。

这是代码

/* Loop runs twice, from 0 to 1 */
for(var AccountIndex in walletForm.masterpublicKey){
/* Bunch of code, then... */

/* Construct an API call to Insight */
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://insight.bitpay.com/api/addrs/" + stringOfAddresses + "/txs?from=0&to=100", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
$scope.$apply(function () {
txListInsight.txs[AccountIndex] = ( JSON.parse(xhr.responseText));
/* Set semaphore */
txListInsight.txsReady[AccountIndex] = true;
parseTransactions(AccountIndex);
console.log(txList);
})
}
}
xhr.send();
}

我什至可以在 Chrome Dev Console 的网络选项卡中看到这两个请求,并且响应都是正确的。为什么我只收到一次回调而不是两次?我的第二个回调是否覆盖了对第一个回调的引用?

为什么网上有个图书馆叫“AsyncXMLHttpRequest ”?我也在使用 AngularJS——我应该看看“ promise ”吗?

另一种选择是通过将我的两个 API 请求合并为一个来完全避免该问题,但我不确定字符数限制是多少。

最佳答案

我认为用当前的 AccountIndex 显式调用函数应该可以,注意闭包

var xhrs = {};
for(var AccountIndex in walletForm.masterpublicKey){
(function(AccountIndex) {

xhrs[AccountIndex] = new XMLHttpRequest();
xhrs[AccountIndex].open("GET", "https://insight.bitpay.com/api/addrs/" + stringOfAddresses + "/txs?from=0&to=100", true);
xhrs[AccountIndex].onreadystatechange = function() {
if (xhrs[AccountIndex].readyState == 4) {
$scope.$apply(function () {
txListInsight.txs[AccountIndex] = ( JSON.parse(xhrs[AccountIndex].responseText));
/* Set semaphore */
txListInsight.txsReady[AccountIndex] = true;
parseTransactions(AccountIndex);
console.log(txList);
})
}
}
xhrs[AccountIndex].send();
})(AccountIndex);
}

关于javascript - 并行同步 XMLHttpRequests 只回调一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418530/

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