我有一个temp
数组的以太坊地址。我想用一个返回promise(web3方法)的函数映射这个数组。在Promise.all
之后,承诺仍然悬而未决。我不明白为什么。
以下是我的相关代码:
var prom = temp.map(x => [x, self.getBalance(x)]);
Promise.all(prom).then(function(results) {
console.log(results)
});
getBalance(t){
return this.contract.methods.balanceOf(t).call().then(function (result) {
return result / Math.pow(10, 18);
}).catch(function(e) {
console.log('error: '+e);
});
}
结果:
[ [ '0x92c9F71fBc532BefBA6dA4278dF37CC3A81c1fAD',
Promise { <pending> } ],
[ '0x910a2b76F4979FeBB4b589fA8D55e6866f4e565D',
Promise { <pending> } ] ]
答案 0 :(得分:4)
如果您想在退回的结果中加入x
,只需在第一个承诺中添加then()
并将其包含在内:
let temp =['0x92c9F71fBc532BefBA6dA4278dF37CC3A81c1fAD','0x910a2b76F4979FeBB4b589fA8D55e6866f4e565D'];
// return x with the promise result
var prom = temp.map(x => getBalance(x).then(r => [x,r]));
Promise.all(prom).then(function(results) {
console.log(results)
});
function getBalance(x){
// fake get balance
return Promise.resolve(Math.random() + 10)
}
答案 1 :(得分:3)
你在地图中返回一个数组数组,而不是一系列的promises,它应该是:
var prom = temp.map(x => self.getBalance(x));
Promise.all(prom).then(function(balances) {
console.log(balances.map((balance, i) => [temp[i], balance]));
});
或使用async/await
const prom = temp.map(async x => [x, await getBalance(x)]);
Promise.all(prom)
.then(balances => console.log(balances));
const temp = [
'0x92c9F71fBc532BefBA6dA4278dF37CC3A81c1fAD',
'0x910a2b76F4979FeBB4b589fA8D55e6866f4e565D'
];
const getBalance = address => {
return Promise.resolve(Math.random());
};
const prom = temp.map(async x => [x, await getBalance(x)]);
Promise.all(prom)
.then(balances => console.log(balances));
&#13;