0

我是 javascript 的初学者,所以请多多包涵。我想知道如何以正确的方式放置 async() 事件。我有 2 个代码片段,我想异步而不是同步执行。代码片段使用了一个执行 HTTP 请求的库,所以这是我无法控制的。

所以我喜欢这两个代码片段以某种方式并行执行。我所拥有的是这 2 个代码片段,我也认为我理解我只想声明前 2 行一次,因为这些行需要时间:

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

2个代码片段如下

代码片段1:

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

(async () => {
            try{
       const exchange = new ccxt.one({ enableRateLimit: true })
       const tickers = await exchange.fetchTickers()
       const obj = { tickers }
       const fs = require('fs');
       fs.writeFile("/myproject/file1.txt", JSON.stringify(obj), function(err) { });
       }catch{}
}) ()

代码片段2:

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

(async () => {
            try{
       const exchange = new ccxt.two({ enableRateLimit: true })
       const tickers = await exchange.fetchTickers()
       const obj = { tickers }
       const fs = require('fs');
       fs.writeFile("/myproject/file2.txt", JSON.stringify(obj), function(err) { });
       }catch{}
}) ()

4

3 回答 3

1

我尝试了这段代码,它实际上是并行完成的。它执行得非常快。

如果您有任何想法要添加代码以使其更加高效,我会很高兴听到如何做到这一点。(例如开放更多端口或任何其他瓶颈?)

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

(async () => {
            try{
       const exchange = new ccxt.one({ enableRateLimit: true })
       const tickers = await exchange.fetchTickers()
       const obj = { tickers }
       const fs = require('fs');
       fs.writeFile("/myproject/file1.txt", JSON.stringify(obj), function(err) { });
       }catch{}
}) ();

(async () => {
            try{
       const exchange = new ccxt.two({ enableRateLimit: true })
       const tickers = await exchange.fetchTickers()
       const obj = { tickers }
       const fs = require('fs');
       fs.writeFile("/myproject/file2.txt", JSON.stringify(obj), function(err) { });
       }catch{}
}) ();

于 2019-02-15T23:02:50.953 回答
0

我不清楚你想要发生什么,但你的代码不会捕捉到所有错误。我知道您似乎忽略了所有错误,但以防万一,...

如果你打算使用 async/await 那么你应该全力以赴。这意味着你应该使用fs.promises.readFilenot fs.readFile。要么,要么您应该fs.readFile手动或使用util.promisify.

所以代码变成了

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

const thing1 = (async () => {
   try{
       const exchange = new ccxt.one({ enableRateLimit: true })
       const tickers = await exchange.fetchTickers()
       const obj = { tickers }
       const fs = require('fs');
       await fs.promises.writeFile("/myproject/file1.txt", JSON.stringify(obj));
   } catch {
      // catch error here
   }
}) ();

const thing2 = (async () => {
    try{
       const exchange = new ccxt.two({ enableRateLimit: true })
       const tickers = await exchange.fetchTickers()
       const obj = { tickers }
       const fs = require('fs');
       await fs.promises.writeFile("/myproject/file2.txt", JSON.stringify(obj));
    } catch {
      // catch error here
    }
}) ();

如果想要同时等待这两件事,那么您可以Promise.all通过传入一个数组来使用,该数组包含两个异步函数返回的每个 Promise。

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

const thing1 = (async () => {
   try{
       const exchange = new ccxt.one({ enableRateLimit: true })
       const tickers = await exchange.fetchTickers()
       const obj = { tickers }
       const fs = require('fs');
       await fs.promises.writeFile("/myproject/file1.txt", JSON.stringify(obj));
   } catch {
      // catch error here
   }
}) ();

const thing2 = (async () => {
    try{
       const exchange = new ccxt.two({ enableRateLimit: true })
       const tickers = await exchange.fetchTickers()
       const obj = { tickers }
       const fs = require('fs');
       await fs.promises.writeFile("/myproject/file2.txt", JSON.stringify(obj));
    } catch {
      // catch error here
    }
}) ();

(async() => {
  await Promise.all([thing1, thing2]);

  // do something after thing1 and thing2
}) ();

当然,除了文件名之外,这两个函数是相同的

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

async function fetchTickersAndWrite({method, filename}) {
   try{
       const exchange = new ccxt[method]({ enableRateLimit: true })
       const tickers = await exchange.fetchTickers()
       const obj = { tickers }
       const fs = require('fs');
       await fs.promises.writeFile(filename, JSON.stringify(obj));
   } catch {
      // catch error here
   }
}

(async() => {
  await Promise.all([
    { method: 'one', filename: `/myproject/file1.txt` },
    { method: 'two', filename: `/myproject/file2.txt` },
  ].map(fetchTickersAndWrite));

  // do something
}) ();
于 2019-07-25T03:38:13.920 回答
0

使用Promise.all

'use strict';

const ccxt = require ('ccxt')
const fs   = require('fs')

async function work (exchangeId) {
    try {
        const exchange = new ccxt[exchangeId] ({ enableRateLimit: true })
        const tickers = await exchange.fetchTickers ()
        const obj = { tickers }
        const filename = exchangeId + '.txt'
        fs.writeFileSync (filename, JSON.stringify (obj))
        console.log ('saved', filename)
    } catch {
    }
}

(async () => {
    const exchangeIds = [ 'bittrex', 'bitfinex' ]
    await Promise.all (exchangeIds.map (exchangeId => work (exchangeId)))
}) ()

于 2019-07-25T03:22:35.710 回答