为Promise.all()动态创建数组

时间:2017-11-30 17:00:08

标签: javascript asynchronous promise

我必须多次调用异步函数(但调用的数量是动态的)。出于某种原因,对Promise.all()数组getPricesCalls中的函数使用此方法实际上不会触发。

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

0 个答案:

没有答案