Node.js - Can`t Get Async Throws With Try/catch Blocks
Solution 1:
async functions always return promises. In fact, they always return native promises (even if you returned a bluebird or a constant). The point of async/await is to reduce the version of .then
callback hell. Your program will still have to have at least one .catch
in the main function to handle any errors that get to the top.
It is really nice for sequential async calls, e.g.;
asyncfunctiona() { /* do some network call, return a promise */ }
asyncfunctionb(aResult) { /* do some network call, return a promise */ }
asyncfunctionc() {
const firstRes = (await (a() /* promise */) /* not promise */);
const secondRes = awaitb(firstRes/* still not a promise*/);
}
You cannot await
something without being inside a function. Usually this means your main
function, or init
or whatever you call it, is not async. This means it cannot call await
and must use .catch
to handle any errors or else they will be unhandled rejections. At some point in the node versions, these will start taking out your node process.
Think about async
as returning a native promise - no matter what - and await
as unwrapping a promise "synchronously".
note async functions return native promises, which do not resolve or reject synchronously:
Promise.resolve(2).then(r => console.log(r)); console.log(3); // 3 printed before 2 Promise.reject(new Error('2)).catch(e => console.log(e.message)); console.log(3); // 3 before 2
async functions return sync errors as rejected promises.
asyncfunctiona() { thrownewError('test error'); } // the following are true if a is defined this way tooasyncfunctiona() { returnPromise.reject(newError('test error')); } /* won't work */try { a() } catch(e) { /* will not run */ } /* will work */try { awaita() } catch (e) { /* will run */ } /* will work */a().catch(e =>/* will run */) /* won't _always_ work */try { returna(); } catch(e) { /* will not usually run, depends on your promise unwrapping behavior */ }
Solution 2:
Main must be an async function to catch async errors
// wont workletmain = () =>{
try{
test();
}catch(error){
console.log("error in main() =", error);
}
}
// will worklet main = async () =>{
try{
test();
}catch(error){
console.log("error in main() =", error);
}
}
Post a Comment for "Node.js - Can`t Get Async Throws With Try/catch Blocks"