Javascript 停止Puppeter进程,直到全局var值从false变为某个字符串
我在我的nodejs服务器中运行木偶程序。。。这个想法是打开一个页面,通过socket.io读取并发送captcha给用户,当用户收到键入的captcha值时,就可以继续进行木偶游戏了。。。这是我的代码的简化版本Javascript 停止Puppeter进程,直到全局var值从false变为某个字符串,javascript,puppeteer,Javascript,Puppeteer,我在我的nodejs服务器中运行木偶程序。。。这个想法是打开一个页面,通过socket.io读取并发送captcha给用户,当用户收到键入的captcha值时,就可以继续进行木偶游戏了。。。这是我的代码的简化版本 var captcha = false ; io.on('connection' , function(socket){ socket.on('start_puppeteer' , function (data) { io.em
var captcha = false ;
io.on('connection' , function(socket){
socket.on('start_puppeteer' , function (data) {
io.emit('push_msg' , {text : 'starting puppeteer .... ' });
run(io);
})
socket.on('get_captcha_from_client' , function (data) {
captcha = data.text ;
console.log( 'capthca set : ' + captcha);
})
});
function get_captcha() {
return new Promise(function(resolve , reject ) {
if(captcha === false )
reject(captcha );
else
resolve(captcha);
});
}
async function run(io) {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('http://localhost');
console.log( ' sending captcha to client ' );
io.emit('send_captcha_to_client' , {text : 'captcha text' });
var captcha = await get_captcha();
console.log( ' captcha confirm -> ' + captcha );
browser.close();
}
问题是,即使设置了验证码,代码也不会移动,我也不会在控制台中获得captcha confirm
$ node pop.js
sending captcha to client
(node:9356) UnhandledPromiseRejectionWarning: false
(node:9356) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
(rejection id: 3)
(node:9356) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
capthca set : 1234
page.waitForFunction
对函数求值,也就是说,您可以检查某个DOM节点的存在或输入值,但您只能访问该函数内部的页面对象
现在,如果您只想等待验证码被解决,请让您的获取验证码
返回承诺
并等待其结果:
function get_captcha() {
return new Promise(resolve => {
// ...Do something lengthy here...
resolve(captcha);
});
}
async function run(io) {
// ....
await page.goto('http://localhost');
io.emit('send_captcha_to_client' , {text : 'captcha text' });
var captcha = await get_captcha();
// ....
}
thanx给@Vaviloff和@yaniv efraim我解决了这样的问题
var fullfillCaptcha;
var captchaPromise = new Promise(resolve => fullfillCaptcha = resolve);
socket.on('get_captcha_from_client' , function (data) {
fullfillCaptcha(data.text);
})
和内部异步函数运行
var captcha = await captchaPromise;
thanx,我对我四处寻找并做了我认为正确的事情的承诺一无所知。。。。但我不能得到通过承诺。。。我更新了我的问题并发布了全部代码。。。请看一看