gpt4 book ai didi

javascript - 使事件发射器同步

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:56:34 26 4
gpt4 key购买 nike

我正在试用包 proxy-lists ,它使用事件发射器来接收代理。

我创建了以下示例:

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

function main() {

const options = {
countries: null
};

// `gettingProxies` is an event emitter object.
const gettingProxies = ProxyLists.getProxies(options);

let data = []
gettingProxies.on('data', function (proxies) {
console.log(proxies);
data.push(proxies)
if (data.length > 1000) {
return data
}
});
}

console.log("First Call");
const res = main()
console.log(res);
console.log("Last Call");

但是,我收到以下输出:

First Call
undefined
Last Call
[ { ipAddress: 'ip-192-169-156-211.ip.secureserver.net',
port: 52324,
country: null,
source: 'rosinstrument' },
{ ipAddress: 'ip-192-169-218-61.ip.secureserver.net',

如您所见,函数运行时已调用 console.log。但是,我更喜欢以下同步顺序:

First Call
[ { ipAddress: '72.89.213.193.static.cust.telenor.com',
port: 51024,
country: 'us',
source: 'rosinstrument' },
{ ipAddress: '50.250.56.129',
port: 48380,
country: 'us',
source: 'rosinstrument' },
...
Last Call

对我做错了什么有什么建议吗?

最佳答案

我认为您可以将异步代码包装到 Promise 中,并使用您正在等待的值resolve 它,然后然后 调用您需要的下一个代码,如下所示:

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

function main() {
return new Promise((resolve, reject) => {
const options = {
countries: null
};

// `gettingProxies` is an event emitter object.
const gettingProxies = ProxyLists.getProxies(options);

let data = []

gettingProxies.on('data', function (proxies) {
console.log(proxies);
data.push(proxies)
if (data.length > 1000) {
resolve(data);
}
});
})
}

console.log("First Call");

main().then((res) => {
console.log(res);
console.log("Last Call");
})

如果你正在使用 babel 或 typescript 之类的东西,你甚至可以像这样以其他方式使用 async/await:

console.log("First Call");
var res = await main();
console.log(res);
console.log("Last Call");

关于javascript - 使事件发射器同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56554887/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com