javascript - 在 map 函数中使用 Promise
问题描述
我有一temp
组以太坊地址。我想用一个返回承诺的函数(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> } ] ]
解决方案
如果您想包含x
在返回的结果中,只需then()
在第一个 Promise 中添加 a 并包含它:
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)
}
推荐阅读
- python - Python不会关闭excel工作簿
- bash - 等效于 GitLab CI/CD 中的健康检查测试
- string - Flutter 如何生成随机字符串
- tsql - TSQL中包含子表的数据结果表?
- azure - 在 Azure CDN 规则引擎中筛选用户代理
- javascript - 将 PhP 变量存储在 JavaScript 变量中
- c# - 以 netstandard2.0 为目标时的 FileNotFoundException 程序集,但在多目标时不是
- bash - 使用 bash 预处理 gnuplot 脚本
- excel - 用户表单中的VBA退出子而不将先前完成的字段保存到工作表
- php - 想要 index.php 在加载时加载