在地图函数中使用承诺

Using promises in a map function

我有一个 temp 以太坊地址数组。我想用一个 returns 承诺(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> } ] ]

您在地图中返回的是一组数组,而不是一组承诺,它应该是:

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));

如果您想在返回结果中包含 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)
}