Reputation: 125
I have an Array of orders and want to loop inside the array and call an async function to check each order and then render the array inside the dom.dow is my code
I try to create an array outside of mapping and push valid orders to the array but when I log the array its empty
renderTrades = () => {
const { trades } = this.props;
const contractWrappers = new ContractWrappers(web3Wrapper._provider, { networkId: KOVAN_NETWORK_ID });
const _trade = [];
trades.map((trade, index) => {
contractWrappers.exchange.getOrderInfoAsync(trade.order)
.then((val) => {
if (val.orderStatus == 5) {
_trade.push(<TradeRow0x key={index} />);
}
});
});
return _trade;
};
I want to push valid orders to the array and render it into the dom
Upvotes: 0
Views: 4347
Reputation: 469
Can be achieved using Promise.all()
to await for all of your promises to resolve before returning your required JSX.
// map all of your trades to promises
const tradesPromises = trades.map(trade => contractWrappers.exchange.getOrderInfoAsync(trade.order))
Promise.all(tradesPromises).then(res => {
// all of your promises have now resolved, so you can return your jsx as required.
const mappedTrades = res.map((value, index) => {
return value.orderStatus === 5 ? <TradeRow key={index} /> : null
})
// now you will be able to log these out and see what you are
// expecting as the promises will all have resolved.
console.log(mappedTrades);
})
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all for an in-depth description and example of Promise.all
Upvotes: 1