1

我在让它工作时遇到了一些麻烦。

var Browser = require('zombie');
var browser = new Browser({
 debug: true
})



function getPredictions(){
    var prediction = ['5', '7', '9', '11', '14', '18'];
    for(i in prediction){
        sendPrediction(prediction[i]);
    }
}

function sendPrediction(prediction){
    browser.visit('http://localhost:3000/prediction.php', function (error, browser){
        browser.fill('#prediction', prediction);
        browser.pressButton('Send', function (error, browser){
            if(browser.html == 'correct'){
                console.log('The correct prediction is ' + prediction +'');
            }else{
                console.log('The prediction ' + prediction + ' is incorrect.');
            }
        });
    });
}

getPredictions();

基本上,我从数组传递到服务器的所有四个预测,我希望能够检查它是否是正确的预测。'9' 是正确的预测,但它告诉我即使 browser.html 是“正确的”,它们都是无效的。

我怎样才能让它工作?我究竟做错了什么?

4

1 回答 1

0

我认为您正在重用相同的僵尸浏览器实例。尝试以这种方式重写您的代码。现在该getPrediction方法将“等待”直到前一个完成并解析(注意next参数)。

function getPredictions(){
    var i = -1, prediction = ['5', '7', '9', '11', '14', '18'];
    var next = function() {
        i++;
        if(i < prediction.length)
            sendPrediction(prediction[i], next);
    }
    next();
}

function sendPrediction(prediction, next){
    browser.visit('http://localhost:3000/prediction.php', function (error, browser){
        browser.fill('#prediction', prediction);
        browser.pressButton('Send', function (error, browser){
            if(browser.html == 'correct'){
                console.log('The correct prediction is ' + prediction +'');
            }else{
                console.log('The prediction ' + prediction + ' is incorrect.');
            }
            next();
        });
    });
}

Browser您也可以在每次检查预测时尝试创建一个新实例

function sendPrediction(prediction){
    var browser = new Browser({ debug: true });
    browser.visit('http://localhost:3000/prediction.php', function (error, browser){
        browser.fill('#prediction', prediction);
        browser.pressButton('Send', function (error, browser){
            if(browser.html == 'correct'){
                console.log('The correct prediction is ' + prediction +'');
            }else{
                console.log('The prediction ' + prediction + ' is incorrect.');
            }
        });
    });
}
于 2012-08-29T15:29:49.440 回答