交换同步到循环到异步方法?

时间:2019-02-22 21:23:28

标签: javascript node.js http async-await

我有这段代码,在尝试将必需的内存用于库之前,我尝试在其中缓存这些必需的内存。我缓存了它们,以便在实际执行请求时使代码更快,这对于尽快执行请求至关重要。

代码正在运行,但现在它以“同步”方式处理请求。

我相信问题代码如下所示:

for (i = 0; i < exchanges.length; i++)

我不确定运行上述异步循环的最佳/最快方法是什么?

'use strict';
const ccxt = require('ccxt');
const fs = require('fs');
const path = require('path');

//Cache some memories first
var exchangesArray = [];
var exchangesArray2 = [];
(async () => {
  const allexchanges = ccxt.exchanges.filter((id) => !['coinmarketcap', 'theocean'].includes(id))
        .map(async (id) => {
            const Exchange = ccxt[id];
            const exchange = new Exchange({ enableRateLimit: true });
            if (exchange.has['fetchTickers']) {

                exchangesArray.push(exchange);
                exchangesArray2.push(id);
            }
        });

    await Promise.all(allexchanges);
})();



//The cached memories
const exchanges = exchangesArray; //Holds exchanges object
const exchangesnames = exchangesArray2; //Holds exchanges name
var i;

//Use cached memories to do the "fetchTickers()" as fast as possible now
(async () => {
    console.log(`start`);
    const start = Date.now();


    //What is the fastest way to make this for loop async/await to run in parallel?
    for (i = 0; i < exchanges.length; i++) {

        // pop one exchange from the array
        const exchange = exchanges[i]
        const exchangename = exchangesnames[i]

        try {
            const tickers = await exchange.fetchTickers();
            const dumpFile = path.join(__dirname, 'tickers', `${exchangename}Tickers.json`);
            await fs.promises.writeFile(dumpFile, JSON.stringify(tickers));
        } catch (e) {
            console.error(e);
        }
    }


    // wait for all of them to execute or fail
    await Promise.all(exchanges)


    const end = Date.now();
    console.log(`Done in ${(end - start) / 1000} seconds`);
})();

2 个答案:

答案 0 :(得分:0)

看看for await...of语法。

答案 1 :(得分:0)

尝试一下。基本上,您会为每个操作创建一个承诺数组,以保存您的股票行情。然后使用Promise.all等待所有股票报价流程解决。

//What is the fastest way to make this for loop async/await to run in parallel?
    var tickersPromises = []
    for (i = 0; i < exchanges.length; i++) {

        // pop one exchange from the array
        const exchange = exchanges[i]
        const exchangename = exchangesnames[i]

        try {
            let tickerProcessing = new Promise(async (resolve) => {
                // probably do a try catch in here
                const tickers = await exchange.fetchTickers();
                const dumpFile = path.join(__dirname, 'tickers', `${exchangename}Tickers.json`);
                await fs.promises.writeFile(dumpFile, JSON.stringify(tickers));
                resolve()
            })
            tickersPromises.push(tickerProcessing)

        } catch (e) {
            console.error(e);
        }
    }


    // wait for all of them to execute or fail
    await Promise.all(tickersPromises)

从较高的角度讲,如果您真的想使此代码更快,请停止将响应写入文件,并使用对象或词典库将其存储在内存中。也就是说,网络延迟是最慢的部分。

我猜这些是加密货币交易所。请记住,使用REST API时,股票行情通常会因加密交易而延迟。您最好使用websocket界面,许多交易所提供的这些功能都可以在可能的情况下尽快为您提供最新的行情自动收录器信息。