javascript - Promises not catching error correctly NodeJS -


if remember correctly promises supposed catch error when 1 thrown @ times promise.catch() can used handle error. don't recall exceptions when throw error inside settimeout() somehow doesn't work.

can explain why doesn't work? or bug in nodejs?

test code

// works! function async() {         return new promise(function (resolve, reject) {                 throw new error('test');         }); }  async().catch(function() {         console.log('ok: 1'); });   // doesn't work.. function async_fail() {         return new promise(function (resolve, reject) {                 settimeout(function() {                         throw new error('test');                 }, 1);         }); }  async_fail().catch(function() {         console.log('ok: 2'); }); 

you never catch error thrown in settimeout, because executes async actual execution of promise function. promise finished (without call resolve or reject) when function inside set timeout called.

if want promise fail based on error inside settimeout need catch manually , call reject:

settimeout(function() {      try{           throw new error('test');      }catch(ex){           reject(ex);      } }, 1); 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -