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

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현