2016-06-16 1 views
5

J'essaie de comprendre comment je devrais faire un script nightmare.js en utilisant la logique "if-then". Par exempleNightmare.js la navigation conditionnelle

var Nightmare = require('nightmare'); 
var nightmare = Nightmare({ 
    show: true, 
    paths: { 
     userData: '/dev/null' 
    } 
}); 

nightmare 
    .goto('http://www.example.com/') 
    .wait('h1') 
    .evaluate(function() { 
     return document.querySelector('title').innerText; 
    }) 
    // here: go to url1 if title == '123' otherwise to url2 
    .end() 
    .then(function() { 
     console.log('then', arguments); 

    }).catch(function() { 
     console.log('end', arguments); 
    }); 

Comment faire pour que ce script passe à une autre URL en fonction du résultat de l'évaluation?

Répondre

10

Puisque Nightmare est then, vous pouvez le retourner d'un .then() pour le chaîner comme vous le feriez des promesses ordinaires.

var Nightmare = require('nightmare'); 
var nightmare = Nightmare({ 
    show: true, 
    paths: { 
    userData: '/dev/null' 
    } 
}); 

nightmare 
    .goto('http://www.example.com/') 
    .wait('h1') 
    .evaluate(function() { 
    return document.querySelector('title') 
     .innerText; 
    }) 
    .then(function(title) { 
    if (title == 'someTitle') { 
     return nightmare.goto('http://www.yahoo.com'); 
    } else { 
     return nightmare.goto('http://w3c.org'); 
    } 
    }) 
    .then(function() { 
    //since nightmare is `then`able, this `.then()` will 
    //execute the call chain described and returned in 
    //the previous `.then()` 
    return nightmare 
     //... other actions... 
     .end(); 
    }) 
    .then(function() { 
    console.log('done'); 
    }) 
    .catch(function() { 
    console.log('caught', arguments); 
    }); 

Si vous voulez un plus logique synchrone à la recherche, vous voudrez peut-être envisager d'utiliser generators avec vo ou co. Par exemple, ce qui précède a été réécrit avec vo:

var Nightmare = require('nightmare'); 
var vo = require('vo'); 

vo(function *() { 
    var nightmare = Nightmare({ 
    show: true, 
    paths: { 
     userData: '/dev/null' 
    } 
    }); 

    var title = yield nightmare 
    .goto('http://www.example.com/') 
    .wait('h1') 
    .evaluate(function() { 
     return document.querySelector('title') 
     .innerText; 
    }); 

    if (title == 'someTitle') { 
    yield nightmare.goto('http://www.yahoo.com'); 
    } else { 
    yield nightmare.goto('http://w3c.org'); 
    } 

    //... other actions... 

    yield nightmare.end(); 
})(function(err) { 
    if (err) { 
    console.log('caught', err); 
    } else { 
    console.log('done'); 
    } 
});