'How to add web3js contract calls to Promise.all()
Ill try to explain this the best I can because I haven't got much experience with Promise, mostly just used async/await
Im building a database and have something like this
let promises = []
for (let j = 0; j < batchSize; j++) {
let token0Address = token0Addresses[j]
let token0Contract = new web3.eth.Contract(abis.token, token0Address)
promises.push(token0Contract.methods.name().call())
}
try {
let token0Names = await Promise.all(promises)
} catch {other stuff}
The issue im running into is that some tokens don't have names which I was hoping would be caught by the try catch block. But sometimes the calls are returned before it reaches the try block and throws an error anyway.
I've also tried something like this
promises.push(() => token0Contract.methods.name().call())
but this just makes Promise.all(promises) return a bunch of functions
I've also tried
promises.push(new Promise(function(resolve, reject) {
resolve(token0Contract.methods.symbol().call())
}))
and
promises.push(new Promise(function(resolve, reject) {
token0Contract.methods.name().call(function(error, result)) {
if (error) {
reject(error)
} else {
resolve(result)
}
}
}))
Solution 1:[1]
Figured out a solution if anyone else ever has this issue
let tokenNameFunctions = []
for (let j = 0; j < batchSize; j++) {
let token0Address = token0Addresses[j]
let token0Contract = new web3.eth.Contract(abis.token, token0Address)
token0NameFunctions.push(() => token0Contract.methods.name().call())
}
let tokenNames = await Promise.allSettled(tokenNameFunctions.map(e => {return f()}))
Don't know if this is the best way to handle something like this but works nonetheless
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Baxter Cooper |
