2017-07-14 31 views
1

我使用throat npm來限制併發性,我想知道如何測試它是否實際工作?就像我的代碼運行良好,但我怎麼能確定它實際上是限制?我如何測試我的併發限制是否在javascript中工作?

這是我的代碼:

const throat = require('throat'); 

readURLsfromFile().then((urls) => { 

    Promise.all(urls.map(
     throat(1, (url, i) => { 
      main(urls[i], i, urls.length) 
     })) 
    ); 
}) 

編輯:我試過圖莎爾的想法,但我不能得到它的工作。也許我沒有正確使用喉嚨?下面是我想要的代碼:如果計數器始終打印1即只有一個進程同時運行

const throat = require('throat')(1); 
var request = require('request'); 
let counter = 0 

throat(() => { 
    counter++ 
    console.log(counter, 1) 
    main(1).then(() => --counter) 
}) 
throat(() => { 
    counter++ 
    console.log(counter, 2) 
    main(2).then(() => --counter) 
}) 
throat(() => { 
    counter++ 
    console.log(counter, 3) 
    main(3).then(() => --counter) 
}) 


function main(i) { 
    return new Promise((resolve,reject) => { 
     request("http://google.com", (err, response, html) => { 
      resolve() 
     }) 
    }) 
} 
+1

將執行次數存儲在作用域外的變量上,然後每當你有'main'函數運行你的'++'計數器,當它超過你'''它'。然後,您可以檢出該變量,以便在給定時間知道您正在執行多少個併發執行。 –

回答

1

簡單設置一個計數器

let counter = 0; // set the counter to zero 
const throat = require('throat'); 

readURLsfromFile().then((urls) => { 

    Promise.all(urls.map(
     throat(1, (url, i) => { 
      counter++; 
      console.log(counter, i); // print counter value and i 
      main(urls[i], i, urls.length); 
     })) 
    ); 
}) 

function main (..........) { ....... --counter; } // decrement the counter value once task is completed 

+0

您最終還需要「櫃檯」。 –

+0

@JuanStiza是啊'''是一個更好的選擇,更新的答案。 –

+0

這麼多「簡單」大聲笑,你有一個錯誤:P – Lansana

相關問題