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)
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 considerreject(err);
`
////////////////////////////////////////////////////////////////////