2016-06-16 9 views
5

मैं समझने की कोशिश कर रहा हूं कि मुझे "if-then" तर्क का उपयोग करके एक nightmare.js स्क्रिप्ट कैसे बनाना चाहिए। उदाहरण के लिएदुःस्वप्न.जेएस सशर्त ब्राउज़िंग

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); 
    }); 

मूल्यांकन के परिणाम के आधार पर मैं इस स्क्रिप्ट को एक अलग यूआरएल में कैसे बना सकता हूं?

उत्तर

10

चूंकि दुःस्वप्न then सक्षम है, इसलिए आप इसे .then() से वापस ले सकते हैं जैसे कि आप सामान्य वादे करेंगे।

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); 
    }); 

आप एक अधिक तुल्यकालिक दिखने तर्क चाहते हैं, आप vo या co साथ generators उपयोग करने पर विचार कर सकते हैं। उदाहरण के लिए, उपरोक्त उपरोक्त 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'); 
    } 
}); 
संबंधित मुद्दे