我正在使用喉咙npm来限制并发性,我想知道如何测试它是否真的有效?就像我的代码运行良好,但我怎么能确定它实际上是限制?
这是我的代码:
const throat = require('throat');
readURLsfromFile().then( (urls) => {
Promise.all(urls.map(
throat(1, (url, i) => {
main(urls[i], i, urls.length)
}))
);
})
编辑:我尝试过Tushar的想法,但我无法让它发挥作用。也许我没有正确使用喉咙?这是我正在尝试的代码:
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()
})
})
}
答案 0 :(得分: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
如果计数器始终打印1,即一次只运行一个进程。