proxy-lists icon indicating copy to clipboard operation
proxy-lists copied to clipboard

Using async/await?

Open CrimsonVex opened this issue 4 years ago • 3 comments

How can I use this library using async/await syntax?

CrimsonVex avatar Apr 30 '20 11:04 CrimsonVex

Might've worked it out:

const ProxyLists = require('proxy-lists');

const getProxyList = options => {
    return new Promise((resolve, reject) => {
        ProxyLists.getProxies(proxyListOptions).on('data', function(_proxies) {
            resolve(_proxies);
        }).on('error', function(_error) {
            reject(_error);
        });
     });
};
         
var proxyList = await getProxyList();

CrimsonVex avatar Apr 30 '20 11:04 CrimsonVex

Hello, @Sasstraliss There are a couple problems with the code snippet above:

  • The module name is "proxy-lists" not "ProxyLists" - see the require() statement.
  • The "data" event will fire many times - not just once

If you really want to use async/await you can buffer the proxies you've received via the "data" event and then resolve your promise with all the proxies.

chill117 avatar May 19 '20 17:05 chill117

This is an example for an async function

const ProxyLists = require('proxy-lists');

const getProxyList = () => {
	return new Promise(resolve => {
		let proxies = [];
		ProxyLists.getProxies({ protocols: ['https'] })
			.on('data', p => p.forEach(p => proxies.push(`${p.ipAddress}:${p.port}`)))
			.once('end', () => resolve(proxies));
	})
};

const run = async () => {
	const proxyList = await getProxyList();
	console.log(proxyList);
};

run();

0-don avatar Mar 23 '21 21:03 0-don