LucianoGanga / simple-headless-chrome

Simple abstraction to use Chrome as a Headless Browser with Node JS
MIT License
217 stars 50 forks source link

Program unable to catch the error thrown by waitForPageToLoad() #91

Open pofengliu opened 6 years ago

pofengliu commented 6 years ago

The way the throw err; inside a Promise constructor which can't be caught by application thus terminate the main thread. Two scenarios listed for comparison, probably should consider reject(err);

`

const promiseTimeout = function (promise, timeout) { ... // https://stackoverflow.com/questions/30936824/what-is-the-best-general-practice-to-timeout-a-function-in-promise ... // Handles the timeout internally, clearing it when the promise resolves. ... // It prevents the library to hang until the timeout is resolved ... var timer = null; ... return Promise.race([new Promise(function (resolve, reject) { ..... timer = setTimeout(function () { ....... var err = new Error('[Headless Chrome] Timeout after ' + timeout + ' ms'); ....... err.code = 'TIMEOUT'; ....... reject(err); // <== use reject() here!!!!!!!!! ....... }, timeout); ..... return timer; ..... }), promise.then(function (value) { ..... clearTimeout(timer); ..... return value; ..... })]); ... } undefined

var foo = promiseTimeout(new Promise(function(resolve, reject) { ... setTimeout(function() { ..... return resolve(42) ..... }, 2000) ... }), 1000).catch(err => console.log(err.stack)) undefined Error: [Headless Chrome] Timeout after 1000 ms at Timeout._onTimeout (repl:8:17) at ontimeout (timers.js:458:11) at tryOnTimeout (timers.js:296:5) at Timer.listOnTimeout (timers.js:259:5)

////////////////////////////////////////////////////////////////////

const promiseTimeout = function (promise, timeout) { ... // https://stackoverflow.com/questions/30936824/what-is-the-best-general-practice-to-timeout-a-function-in-promise ... // Handles the timeout internally, clearing it when the promise resolves. ... // It prevents the library to hang until the timeout is resolved ... var timer = null; ... return Promise.race([new Promise(function (resolve, reject) { ..... timer = setTimeout(function () { ....... var err = new Error('[Headless Chrome] Timeout after ' + timeout + ' ms'); ....... err.code = 'TIMEOUT'; ....... throw err; ....... }, timeout); ..... return timer; ..... }), promise.then(function (value) { ..... clearTimeout(timer); ..... return value; ..... })]); ... } undefined

var foo = promiseTimeout(new Promise(function(resolve, reject) { ... setTimeout(function() { ..... return resolve(42) ..... }, 2000) ... }), 1000).catch(err => console.log(err.stack)) undefined Error: [Headless Chrome] Timeout after 1000 ms`