gpt4 book ai didi

javascript - 包含在 for 循环中困惑的 Promise 的对象数组

转载 作者:行者123 更新时间:2023-12-03 07:28:19 25 4
gpt4 key购买 nike

我有一个带有狗狗币地址的对象数组:

var wallets = [
{ address: 'DT2rmMrutwzdZ8EXwzj4QFdcL6DtvGGkci'},
{ address: 'DMoonjyH1aHLZc1kksmikBUhjXromn1ZN4'}
];

我还有一个简单的http请求功能:

function get(url) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
if (req.status == 200) {
resolve(req.response);
}
else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send();
});
}

我尝试向数组中的每个对象添加新属性 wallets包含 Promise/API 响应,使用 for 循环:

for (i in wallets){
var balance = get('https://dogechain.info/api/v1/address/balance/'+wallets[i].address)
.then(
function(response){
wallets[i].balance = response;
},
function(error) {
wallets[i].balance = error;
}
);
};

console.log(wallets);

但在每次迭代中,当 Promise 得到解决时,for 循环就会结束,并将响应分配给最后一个对象。

我想要的是这样的数组:

[
{ address: 'DT2rmMrutwzdZ8EXwzj4QFdcL6DtvGGkci', balance: -balance from api response-},
{ address: 'DMoonjyH1aHLZc1kksmikBUhjXromn1ZN4', balance: -balance from api response-}
]

最佳答案

第一观察发现返回值是一个字符串而不是一个对象。

resolve(req.response);

更改为

resolve(JSON.parse(req.response));

如果我理解的话,你想用所有 Promises 响应填充数组。

   var wallets = [
{ address: 'DT2rmMrutwzdZ8EXwzj4QFdcL6DtvGGkci'},
{ address: 'DMoonjyH1aHLZc1kksmikBUhjXromn1ZN4'}
];


listPromises = wallets.map(function (wallet){
var balance = get('https://dogechain.info/api/v1/address/balance/'+wallet.address)
.then(function(response){
return {
address: wallet.address,
balance: response.balance
};
},
function(error) {
return {
address: wallet.address,
balance: error
}
}
);
return balance
});


Promise.all(listPromises)
.then(function(responseWallets){
console.log(responseWallets);
// add your script to continue

});

function get(url) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
if (req.status == 200) {
resolve(JSON.parse(req.response));
}
else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send();
});
}

希望对您有帮助。享受吧!

我在@Bergi之后简化了脚本建议。

关于javascript - 包含在 for 循环中困惑的 Promise 的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35911114/

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