I've pasted two almost same codes with one little difference, one works just fine but the other gives UnhandledPromiseRejectionWarning.
async function promise () {
return new Promise((resolve, reject) => {
throw new Error();
resolve();
reject();
})
}
promise().then((data) =>{console.log('then')}).catch((err)=>{console.log('from the catch')});
The output is :
> node index.js
from the catch
But for this case
function promise () {
return new Promise(async (resolve, reject) => {
throw new Error();
resolve();
reject();
})
}
promise().then((data) =>{console.log('then')}).catch((err)=>{console.log('err')});
The output is something like this
> node index.js
(node:98195) UnhandledPromiseRejectionWarning: Error
at /home/parthiv/Projects/exp/index.js:47:11
at new Promise (<anonymous>)
at promise (/home/parthiv/Projects/exp/index.js:46:10)
at Object.<anonymous> (/home/parthiv/Projects/exp/index.js:53:1)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47
(Use `node --trace-warnings ...` to show where the warning was created)
(node:98195) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:98195) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Can someone explain this behaviour of an async function inside the promise ?