I have to call an asynchronous function multiple times (but the number of calls is dynamic). For some reason, using this approach for the Promise.all()
the functions in the array getPricesCalls
don't actually fire.
var getPrice = function (exchange, product) {
var priceData = {};
return new Promise(function (resolve, reject) {
if (exchange == 'GDAX') {
const gdaxPublicClient = new Gdax.PublicClient(product);
gdaxPublicClient.getProductTicker((error, response, data) => {
if (error) {
reject(Error(error));
} else {
console.log("GDAX ", product, ": ", data['price']);
priceData[exchange] = {
product: parseFloat(data['price'])
}
resolve(priceData);
}
});
}
if (exchange == 'POLONIEX') {
poloniex.returnTicker(function (err, data) {
if (err) {
reject(Error(error));
} else {
console.log("POLONIEX ", product, ": ", data[product]['last']);
priceData[exchange] = {
product: parseFloat(data[product]['last'])
}
resolve(priceData);
}
});
}
});
}
var exchanges = ['GDAX', 'POLONIEX'];
var gdaxProducts = ['BTC-USD', 'ETH-BTC', 'LTC-BTC'];
var poloniexProducts = ['USDT_BTC', 'BTC_ETH', 'BTC_LTC'];
var products = {
"GDAX": gdaxProducts,
"POLONIEX": poloniexProducts
}
var gdaxPrices = {};
var poloPrices = {};
var getPricesCalls = [];
for (var exch in exchanges) {
for (var product in products) {
var functionCall = getPrice(exch, product);
getPricesCalls.push(functionCall);
}
}
// Manually creating the array works:
// var getPricesCalls = [getPrice(exchanges[0], gdaxProducts[0]), getPrice(exchanges[1], poloniexProducts[1])];
Promise.all(getPricesCalls).then(function (results) {
console.log(results);
}, function (err) {
console.error(err);
});