Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using promises in a map function

I have a temp array of ethereum addresses. I want to map this array with a function that returns a promise (web3 method). After Promise.all the promises are still pending. I have no idea why.

Here is my relevant code:

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

Result:

[ [ '0x92c9F71fBc532BefBA6dA4278dF37CC3A81c1fAD',
    Promise { <pending> } ],
  [ '0x910a2b76F4979FeBB4b589fA8D55e6866f4e565D',
    Promise { <pending> } ] ]
like image 362
kasper Taeymans Avatar asked Dec 10 '25 06:12

kasper Taeymans


2 Answers

If you want to include x in your returned results, just add a then() to the first promise and include it:

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)
}
like image 192
Mark Avatar answered Dec 11 '25 19:12

Mark


You're returning an array of arrays in your map, instead of an array of promises, it should be:

var prom = temp.map(x => self.getBalance(x));
Promise.all(prom).then(function(balances) {
   console.log(balances.map((balance, i) => [temp[i], balance]));
});

Or using 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));
like image 34
Marcos Casagrande Avatar answered Dec 11 '25 18:12

Marcos Casagrande



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!