NodeJS 在map函数中使用promise

tzxcd3kk  于 2023-05-06  发布在  Node.js
关注(0)|答案(2)|浏览(188)

我有一个temp以太坊地址数组。我想用一个返回promise的函数(web3方法)Map这个数组。在Promise.all之后,promise仍然是pending。我不知道为什么。
下面是我的相关代码:

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

ki0zmccv1#

如果你想在返回的结果中包含x,只需在第一个promise中添加一个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)
}
erhoui1w

erhoui1w2#

你在map中返回一个数组的数组,而不是一个promise的数组,它应该是:

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

相关问题