kasper Taeymans
kasper Taeymans

Reputation: 7026

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> } ] ]

Upvotes: 3

Views: 241

Answers (2)

Marcos Casagrande
Marcos Casagrande

Reputation: 40404

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

Upvotes: 3

Mark
Mark

Reputation: 92440

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

Upvotes: 4

Related Questions