如何异步/并行执行这两个代码段

时间:2019-02-15 22:39:20

标签: javascript asynchronous

我是javascript的初学者,请耐心等待。我想知道如何以正确的方式放置async()事件。 我有2个代码片段,我想异步而不是同步执行。这些代码段使用一个执行HTTP请求的库,因此这超出了我的控制范围。

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

'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{}
}) ()

3 个答案:

答案 0 :(得分: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{}
}) ();

答案 1 :(得分:0)

我不清楚您想要发生什么,但是您的代码无法捕获所编写的所有错误。我知道您似乎忽略了所有错误,但以防万一,...

如果要使用异步/等待,则应该全部使用。这意味着应该使用fs.promises.readFile而不是fs.readFile。要么手动,要么使用fs.readFileutil.promisify包装在一个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
    }
}) ();

如果希望两者都等待,那么您可以通过传递包含两个异步函数返回的每个promise的数组来使用Promise.all

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

答案 2 :(得分:-1)

使用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)))
}) ()