Why redefining the variable not throwing the error in async functionIs it possible to catch exceptions thrown in a JavaScript async callback?Why would a JavaScript variable start with a dollar sign?Is there a standard function to check for null, undefined, or blank variables in JavaScript?Check if a variable is of function typeWhy aren't ◎ܫ◎ and ☺ valid JavaScript variable names?npm throws error without sudoWhy is my variable unaltered after I modify it inside of a function? - Asynchronous code referenceWhy do we need middleware for async flow in Redux?Call async/await functions in parallelSyntax for async arrow functionWait for data from external API before making POST request

How is it possible for the induced emf to take negative values in Faraday's Law of induction?

Weight functions in graph algorithms

A Real World Example for Divide and Conquer Method

Where can I find standards for statistical acronyms and whether they should be capitalized or lower case?

Will a ThunderBolt 3 (USB-C?) to ThunderBolt 2 cable allow me to use a MacBook Pro as second monitor?

What would be the effects of (relatively) widespread precognition on the stock market?

Has anyone ever written a novel or short story composed of only dialogue?

Nilpotent elements of Lie algebra and unipotent groups

ESTA Travel not Authorized. Accepted twice before!

Do pedestrians imitate automotive traffic?

Inside Out and Back to Front

Why didn't Balak request Bilam to bless his own people?

setcounter is not affecting numbering

What does Windows' "Tuning up Application Start" do?

Book in which the "mountain" in the distance was a hole in the flat world

Why are flying carpets banned while flying brooms are not?

What is the simplest instruction set that has a C++/C compiler to write an emulator for?

How was Luke's prosthetic hand in Episode V filmed?

Father as an heir

When we are talking about black hole evaporation - what exactly happens?

What is the origin of "Wonder begets wisdom?"

Animating the result of numerical integration

Killing a star safely

Trivial non-dark twist in dark fantasy



Why redefining the variable not throwing the error in async function


Is it possible to catch exceptions thrown in a JavaScript async callback?Why would a JavaScript variable start with a dollar sign?Is there a standard function to check for null, undefined, or blank variables in JavaScript?Check if a variable is of function typeWhy aren't ◎ܫ◎ and ☺ valid JavaScript variable names?npm throws error without sudoWhy is my variable unaltered after I modify it inside of a function? - Asynchronous code referenceWhy do we need middleware for async flow in Redux?Call async/await functions in parallelSyntax for async arrow functionWait for data from external API before making POST request






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I have below piece of code in my nodejs. Here I have defined screenshot as const and then redefine it as you can see below. Here the issue is my code was neither throwing any error nor being executed further after the console console.log('opopopopopoopoooooopop'). After sometime I figured out the reason is "I have taken `screenshot variable as const".



const handler = async(request, reply) => 
try
const screenshotPath = ''
console.log(request.payload, 'ddddddddddddddddddd')
let folderName = `./public/applications/$applicationId`
let filepath = `$folderName/$className.png`
mkdirp(folderName, async(err) =>
await imageUpload(file, className, filepath)
console.log('oooooooooooooooooooo')
if (err)
return reply( success: false, message: err.message, data: null )

console.log('opopopopopoopoooooopop')
screenshotPath = filepath
console.log(Event)
const screen = await Event.findOne( )
console.log(screen, 'popopopopopoopopooop')
)
catch (err)
console.log( err )
return reply( success: false, message: err.message, data: null )




But the problem is why my code was not throwing the error here. Can someone please help me to get understand this.



Thank you!!!










share|improve this question






















  • Possible duplicate of Is it possible to catch exceptions thrown in a JavaScript async callback?

    – ponury-kostek
    Mar 26 at 12:24











  • did you try to add try-catch block in inner async function?

    – James De Souza
    Mar 26 at 12:27











  • @JamesDeSouza no... can single try catch cannot do this?

    – Profer
    Mar 26 at 12:29











  • apparently not! when you run async method, it's work like another thread. not something to catch with.

    – James De Souza
    Mar 26 at 12:33











  • @JamesDeSouza So is there any way to handle with single catch block?

    – Profer
    Mar 26 at 12:38

















1















I have below piece of code in my nodejs. Here I have defined screenshot as const and then redefine it as you can see below. Here the issue is my code was neither throwing any error nor being executed further after the console console.log('opopopopopoopoooooopop'). After sometime I figured out the reason is "I have taken `screenshot variable as const".



const handler = async(request, reply) => 
try
const screenshotPath = ''
console.log(request.payload, 'ddddddddddddddddddd')
let folderName = `./public/applications/$applicationId`
let filepath = `$folderName/$className.png`
mkdirp(folderName, async(err) =>
await imageUpload(file, className, filepath)
console.log('oooooooooooooooooooo')
if (err)
return reply( success: false, message: err.message, data: null )

console.log('opopopopopoopoooooopop')
screenshotPath = filepath
console.log(Event)
const screen = await Event.findOne( )
console.log(screen, 'popopopopopoopopooop')
)
catch (err)
console.log( err )
return reply( success: false, message: err.message, data: null )




But the problem is why my code was not throwing the error here. Can someone please help me to get understand this.



Thank you!!!










share|improve this question






















  • Possible duplicate of Is it possible to catch exceptions thrown in a JavaScript async callback?

    – ponury-kostek
    Mar 26 at 12:24











  • did you try to add try-catch block in inner async function?

    – James De Souza
    Mar 26 at 12:27











  • @JamesDeSouza no... can single try catch cannot do this?

    – Profer
    Mar 26 at 12:29











  • apparently not! when you run async method, it's work like another thread. not something to catch with.

    – James De Souza
    Mar 26 at 12:33











  • @JamesDeSouza So is there any way to handle with single catch block?

    – Profer
    Mar 26 at 12:38













1












1








1








I have below piece of code in my nodejs. Here I have defined screenshot as const and then redefine it as you can see below. Here the issue is my code was neither throwing any error nor being executed further after the console console.log('opopopopopoopoooooopop'). After sometime I figured out the reason is "I have taken `screenshot variable as const".



const handler = async(request, reply) => 
try
const screenshotPath = ''
console.log(request.payload, 'ddddddddddddddddddd')
let folderName = `./public/applications/$applicationId`
let filepath = `$folderName/$className.png`
mkdirp(folderName, async(err) =>
await imageUpload(file, className, filepath)
console.log('oooooooooooooooooooo')
if (err)
return reply( success: false, message: err.message, data: null )

console.log('opopopopopoopoooooopop')
screenshotPath = filepath
console.log(Event)
const screen = await Event.findOne( )
console.log(screen, 'popopopopopoopopooop')
)
catch (err)
console.log( err )
return reply( success: false, message: err.message, data: null )




But the problem is why my code was not throwing the error here. Can someone please help me to get understand this.



Thank you!!!










share|improve this question














I have below piece of code in my nodejs. Here I have defined screenshot as const and then redefine it as you can see below. Here the issue is my code was neither throwing any error nor being executed further after the console console.log('opopopopopoopoooooopop'). After sometime I figured out the reason is "I have taken `screenshot variable as const".



const handler = async(request, reply) => 
try
const screenshotPath = ''
console.log(request.payload, 'ddddddddddddddddddd')
let folderName = `./public/applications/$applicationId`
let filepath = `$folderName/$className.png`
mkdirp(folderName, async(err) =>
await imageUpload(file, className, filepath)
console.log('oooooooooooooooooooo')
if (err)
return reply( success: false, message: err.message, data: null )

console.log('opopopopopoopoooooopop')
screenshotPath = filepath
console.log(Event)
const screen = await Event.findOne( )
console.log(screen, 'popopopopopoopopooop')
)
catch (err)
console.log( err )
return reply( success: false, message: err.message, data: null )




But the problem is why my code was not throwing the error here. Can someone please help me to get understand this.



Thank you!!!







javascript node.js asynchronous async-await






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 26 at 12:19









ProferProfer

1194 silver badges17 bronze badges




1194 silver badges17 bronze badges












  • Possible duplicate of Is it possible to catch exceptions thrown in a JavaScript async callback?

    – ponury-kostek
    Mar 26 at 12:24











  • did you try to add try-catch block in inner async function?

    – James De Souza
    Mar 26 at 12:27











  • @JamesDeSouza no... can single try catch cannot do this?

    – Profer
    Mar 26 at 12:29











  • apparently not! when you run async method, it's work like another thread. not something to catch with.

    – James De Souza
    Mar 26 at 12:33











  • @JamesDeSouza So is there any way to handle with single catch block?

    – Profer
    Mar 26 at 12:38

















  • Possible duplicate of Is it possible to catch exceptions thrown in a JavaScript async callback?

    – ponury-kostek
    Mar 26 at 12:24











  • did you try to add try-catch block in inner async function?

    – James De Souza
    Mar 26 at 12:27











  • @JamesDeSouza no... can single try catch cannot do this?

    – Profer
    Mar 26 at 12:29











  • apparently not! when you run async method, it's work like another thread. not something to catch with.

    – James De Souza
    Mar 26 at 12:33











  • @JamesDeSouza So is there any way to handle with single catch block?

    – Profer
    Mar 26 at 12:38
















Possible duplicate of Is it possible to catch exceptions thrown in a JavaScript async callback?

– ponury-kostek
Mar 26 at 12:24





Possible duplicate of Is it possible to catch exceptions thrown in a JavaScript async callback?

– ponury-kostek
Mar 26 at 12:24













did you try to add try-catch block in inner async function?

– James De Souza
Mar 26 at 12:27





did you try to add try-catch block in inner async function?

– James De Souza
Mar 26 at 12:27













@JamesDeSouza no... can single try catch cannot do this?

– Profer
Mar 26 at 12:29





@JamesDeSouza no... can single try catch cannot do this?

– Profer
Mar 26 at 12:29













apparently not! when you run async method, it's work like another thread. not something to catch with.

– James De Souza
Mar 26 at 12:33





apparently not! when you run async method, it's work like another thread. not something to catch with.

– James De Souza
Mar 26 at 12:33













@JamesDeSouza So is there any way to handle with single catch block?

– Profer
Mar 26 at 12:38





@JamesDeSouza So is there any way to handle with single catch block?

– Profer
Mar 26 at 12:38












1 Answer
1






active

oldest

votes


















1
















An error within an async function causes the returned Promise to reject.



...but if nothing is using that Promise:






const handler = async () => 
try
const screenshotPath = '';
const callback = async () =>
screenshotPath = 'redefined';

const promise = callback(); // <= promise will reject...
catch (err)
console.log('in catch'); // ...but this never runs

console.log('finished');


handler();





...then nothing happens.



This is called an unhandled promise rejection.




On the other hand, if the same Promise is await-ed, then the catch will get called:






const handler = async () => 
try
const screenshotPath = '';
const callback = async () =>
screenshotPath = 'redefined';

await callback();
catch (err)
console.log('in catch'); // this runs!

console.log('finished');


handler();






So since the error happens in an async callback, the Promise it returns will reject, but since nothing is using that rejected Promise nothing happens.




Solution



It looks like your mkdirp function follows...




the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument




...so you could use Node's util.promisify to create a version of mkdirp that returns a Promise:



const util = require('util');
const mkdirpPromisified = util.promisify(mkdirp);

const handler = async(request, reply) =>
try
let screenshotPath = ''
let folderName = `./public/applications/$applicationId`
let filepath = `$folderName/$className.png`
await mkdirpPromisified(folderName)
await imageUpload(file, className, filepath)
if (err)
return reply( success: false, message: err.message, data: null )

screenshotPath = filepath
const screen = await Event.findOne( )
catch (err)
console.log( err )
return reply( success: false, message: err.message, data: null )







share|improve this answer























  • Thank you I will check

    – Profer
    Mar 26 at 13:10










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55357012%2fwhy-redefining-the-variable-not-throwing-the-error-in-async-function%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1
















An error within an async function causes the returned Promise to reject.



...but if nothing is using that Promise:






const handler = async () => 
try
const screenshotPath = '';
const callback = async () =>
screenshotPath = 'redefined';

const promise = callback(); // <= promise will reject...
catch (err)
console.log('in catch'); // ...but this never runs

console.log('finished');


handler();





...then nothing happens.



This is called an unhandled promise rejection.




On the other hand, if the same Promise is await-ed, then the catch will get called:






const handler = async () => 
try
const screenshotPath = '';
const callback = async () =>
screenshotPath = 'redefined';

await callback();
catch (err)
console.log('in catch'); // this runs!

console.log('finished');


handler();






So since the error happens in an async callback, the Promise it returns will reject, but since nothing is using that rejected Promise nothing happens.




Solution



It looks like your mkdirp function follows...




the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument




...so you could use Node's util.promisify to create a version of mkdirp that returns a Promise:



const util = require('util');
const mkdirpPromisified = util.promisify(mkdirp);

const handler = async(request, reply) =>
try
let screenshotPath = ''
let folderName = `./public/applications/$applicationId`
let filepath = `$folderName/$className.png`
await mkdirpPromisified(folderName)
await imageUpload(file, className, filepath)
if (err)
return reply( success: false, message: err.message, data: null )

screenshotPath = filepath
const screen = await Event.findOne( )
catch (err)
console.log( err )
return reply( success: false, message: err.message, data: null )







share|improve this answer























  • Thank you I will check

    – Profer
    Mar 26 at 13:10















1
















An error within an async function causes the returned Promise to reject.



...but if nothing is using that Promise:






const handler = async () => 
try
const screenshotPath = '';
const callback = async () =>
screenshotPath = 'redefined';

const promise = callback(); // <= promise will reject...
catch (err)
console.log('in catch'); // ...but this never runs

console.log('finished');


handler();





...then nothing happens.



This is called an unhandled promise rejection.




On the other hand, if the same Promise is await-ed, then the catch will get called:






const handler = async () => 
try
const screenshotPath = '';
const callback = async () =>
screenshotPath = 'redefined';

await callback();
catch (err)
console.log('in catch'); // this runs!

console.log('finished');


handler();






So since the error happens in an async callback, the Promise it returns will reject, but since nothing is using that rejected Promise nothing happens.




Solution



It looks like your mkdirp function follows...




the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument




...so you could use Node's util.promisify to create a version of mkdirp that returns a Promise:



const util = require('util');
const mkdirpPromisified = util.promisify(mkdirp);

const handler = async(request, reply) =>
try
let screenshotPath = ''
let folderName = `./public/applications/$applicationId`
let filepath = `$folderName/$className.png`
await mkdirpPromisified(folderName)
await imageUpload(file, className, filepath)
if (err)
return reply( success: false, message: err.message, data: null )

screenshotPath = filepath
const screen = await Event.findOne( )
catch (err)
console.log( err )
return reply( success: false, message: err.message, data: null )







share|improve this answer























  • Thank you I will check

    – Profer
    Mar 26 at 13:10













1












1








1









An error within an async function causes the returned Promise to reject.



...but if nothing is using that Promise:






const handler = async () => 
try
const screenshotPath = '';
const callback = async () =>
screenshotPath = 'redefined';

const promise = callback(); // <= promise will reject...
catch (err)
console.log('in catch'); // ...but this never runs

console.log('finished');


handler();





...then nothing happens.



This is called an unhandled promise rejection.




On the other hand, if the same Promise is await-ed, then the catch will get called:






const handler = async () => 
try
const screenshotPath = '';
const callback = async () =>
screenshotPath = 'redefined';

await callback();
catch (err)
console.log('in catch'); // this runs!

console.log('finished');


handler();






So since the error happens in an async callback, the Promise it returns will reject, but since nothing is using that rejected Promise nothing happens.




Solution



It looks like your mkdirp function follows...




the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument




...so you could use Node's util.promisify to create a version of mkdirp that returns a Promise:



const util = require('util');
const mkdirpPromisified = util.promisify(mkdirp);

const handler = async(request, reply) =>
try
let screenshotPath = ''
let folderName = `./public/applications/$applicationId`
let filepath = `$folderName/$className.png`
await mkdirpPromisified(folderName)
await imageUpload(file, className, filepath)
if (err)
return reply( success: false, message: err.message, data: null )

screenshotPath = filepath
const screen = await Event.findOne( )
catch (err)
console.log( err )
return reply( success: false, message: err.message, data: null )







share|improve this answer















An error within an async function causes the returned Promise to reject.



...but if nothing is using that Promise:






const handler = async () => 
try
const screenshotPath = '';
const callback = async () =>
screenshotPath = 'redefined';

const promise = callback(); // <= promise will reject...
catch (err)
console.log('in catch'); // ...but this never runs

console.log('finished');


handler();





...then nothing happens.



This is called an unhandled promise rejection.




On the other hand, if the same Promise is await-ed, then the catch will get called:






const handler = async () => 
try
const screenshotPath = '';
const callback = async () =>
screenshotPath = 'redefined';

await callback();
catch (err)
console.log('in catch'); // this runs!

console.log('finished');


handler();






So since the error happens in an async callback, the Promise it returns will reject, but since nothing is using that rejected Promise nothing happens.




Solution



It looks like your mkdirp function follows...




the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument




...so you could use Node's util.promisify to create a version of mkdirp that returns a Promise:



const util = require('util');
const mkdirpPromisified = util.promisify(mkdirp);

const handler = async(request, reply) =>
try
let screenshotPath = ''
let folderName = `./public/applications/$applicationId`
let filepath = `$folderName/$className.png`
await mkdirpPromisified(folderName)
await imageUpload(file, className, filepath)
if (err)
return reply( success: false, message: err.message, data: null )

screenshotPath = filepath
const screen = await Event.findOne( )
catch (err)
console.log( err )
return reply( success: false, message: err.message, data: null )







const handler = async () => 
try
const screenshotPath = '';
const callback = async () =>
screenshotPath = 'redefined';

const promise = callback(); // <= promise will reject...
catch (err)
console.log('in catch'); // ...but this never runs

console.log('finished');


handler();





const handler = async () => 
try
const screenshotPath = '';
const callback = async () =>
screenshotPath = 'redefined';

const promise = callback(); // <= promise will reject...
catch (err)
console.log('in catch'); // ...but this never runs

console.log('finished');


handler();





const handler = async () => 
try
const screenshotPath = '';
const callback = async () =>
screenshotPath = 'redefined';

await callback();
catch (err)
console.log('in catch'); // this runs!

console.log('finished');


handler();





const handler = async () => 
try
const screenshotPath = '';
const callback = async () =>
screenshotPath = 'redefined';

await callback();
catch (err)
console.log('in catch'); // this runs!

console.log('finished');


handler();






share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 26 at 13:04









brian-lives-outdoorsbrian-lives-outdoors

14.7k1 gold badge15 silver badges39 bronze badges




14.7k1 gold badge15 silver badges39 bronze badges












  • Thank you I will check

    – Profer
    Mar 26 at 13:10

















  • Thank you I will check

    – Profer
    Mar 26 at 13:10
















Thank you I will check

– Profer
Mar 26 at 13:10





Thank you I will check

– Profer
Mar 26 at 13:10








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55357012%2fwhy-redefining-the-variable-not-throwing-the-error-in-async-function%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript