首页 > 解决方案 > 在 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> } ] ]

标签: javascriptnode.jspromiseweb3

解决方案


如果您想包含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)
}


推荐阅读