Why does async / await function run twice?











up vote
1
down vote

favorite
1












I'm working with express and node.js application. I have a regular router, which:




  • finds myID in DB,

  • if myID exists it tries to addVisit()

  • if error occures (may such table doesn't exist) it catches the error, creates the new table and addVisit() to it.


The router code is below:



    router.get('/:myId', errorHandler(async (req, res, next) => {

console.log(req.params.myId + ' This is myID Params!');

const Domain = DomainModel(db, Sequelize);
const Click = ClickModel(db, `${req.params.myId}_clicks`, Sequelize);

try {
let row = await Domain.findOne({ where: { myId: req.params.myId } });

console.log(row.myId + ' This is myID from DB');

if (row.myId) {
try {
await addVisit(Click, req);
res.sendStatus(200);
} catch (err) {
console.log(`This error fires!`);
if (err.message !== `Validation error`) {
try {
await db.sync();
await addVisit(Click, req);
res.sendStatus(200);
} catch (err) {
console.log(err);
res.sendStatus(400);
}
} else {
res.sendStatus(400);
}
}
} else {
console.log(`No such myId in use`);
res.sendStatus(400);
}
} catch (err) {
console.log(err);
}
})


But the code runs twice! My console.log() shows:



1. ==> 1231231231 This is myID Params!
2. ==> 1231231231 This is myID from DB
3. ==> This error fires!
4. ==> favicon.ico This is myID Params!
5. ==> TypeError: Cannot read property 'myID' of null


If I comment this part of code it runs only one time!



// if (err.message !== `Validation error`) {
// try {
// await db.sync();
// await addVisit(Click, req);
// res.sendStatus(200);
// } catch (err) {
// console.log(err);
// res.sendStatus(400);
// }
// } else {
// res.sendStatus(400);
// }


This is the only place where I use console.log()! This is the simple sample project in which I able to reproduce the behavior. So why does the code runs twice and WHY my params.myID became favicon.ico?










share|improve this question


















  • 1




    Because your browser is sending two requests.
    – tkausl
    2 days ago















up vote
1
down vote

favorite
1












I'm working with express and node.js application. I have a regular router, which:




  • finds myID in DB,

  • if myID exists it tries to addVisit()

  • if error occures (may such table doesn't exist) it catches the error, creates the new table and addVisit() to it.


The router code is below:



    router.get('/:myId', errorHandler(async (req, res, next) => {

console.log(req.params.myId + ' This is myID Params!');

const Domain = DomainModel(db, Sequelize);
const Click = ClickModel(db, `${req.params.myId}_clicks`, Sequelize);

try {
let row = await Domain.findOne({ where: { myId: req.params.myId } });

console.log(row.myId + ' This is myID from DB');

if (row.myId) {
try {
await addVisit(Click, req);
res.sendStatus(200);
} catch (err) {
console.log(`This error fires!`);
if (err.message !== `Validation error`) {
try {
await db.sync();
await addVisit(Click, req);
res.sendStatus(200);
} catch (err) {
console.log(err);
res.sendStatus(400);
}
} else {
res.sendStatus(400);
}
}
} else {
console.log(`No such myId in use`);
res.sendStatus(400);
}
} catch (err) {
console.log(err);
}
})


But the code runs twice! My console.log() shows:



1. ==> 1231231231 This is myID Params!
2. ==> 1231231231 This is myID from DB
3. ==> This error fires!
4. ==> favicon.ico This is myID Params!
5. ==> TypeError: Cannot read property 'myID' of null


If I comment this part of code it runs only one time!



// if (err.message !== `Validation error`) {
// try {
// await db.sync();
// await addVisit(Click, req);
// res.sendStatus(200);
// } catch (err) {
// console.log(err);
// res.sendStatus(400);
// }
// } else {
// res.sendStatus(400);
// }


This is the only place where I use console.log()! This is the simple sample project in which I able to reproduce the behavior. So why does the code runs twice and WHY my params.myID became favicon.ico?










share|improve this question


















  • 1




    Because your browser is sending two requests.
    – tkausl
    2 days ago













up vote
1
down vote

favorite
1









up vote
1
down vote

favorite
1






1





I'm working with express and node.js application. I have a regular router, which:




  • finds myID in DB,

  • if myID exists it tries to addVisit()

  • if error occures (may such table doesn't exist) it catches the error, creates the new table and addVisit() to it.


The router code is below:



    router.get('/:myId', errorHandler(async (req, res, next) => {

console.log(req.params.myId + ' This is myID Params!');

const Domain = DomainModel(db, Sequelize);
const Click = ClickModel(db, `${req.params.myId}_clicks`, Sequelize);

try {
let row = await Domain.findOne({ where: { myId: req.params.myId } });

console.log(row.myId + ' This is myID from DB');

if (row.myId) {
try {
await addVisit(Click, req);
res.sendStatus(200);
} catch (err) {
console.log(`This error fires!`);
if (err.message !== `Validation error`) {
try {
await db.sync();
await addVisit(Click, req);
res.sendStatus(200);
} catch (err) {
console.log(err);
res.sendStatus(400);
}
} else {
res.sendStatus(400);
}
}
} else {
console.log(`No such myId in use`);
res.sendStatus(400);
}
} catch (err) {
console.log(err);
}
})


But the code runs twice! My console.log() shows:



1. ==> 1231231231 This is myID Params!
2. ==> 1231231231 This is myID from DB
3. ==> This error fires!
4. ==> favicon.ico This is myID Params!
5. ==> TypeError: Cannot read property 'myID' of null


If I comment this part of code it runs only one time!



// if (err.message !== `Validation error`) {
// try {
// await db.sync();
// await addVisit(Click, req);
// res.sendStatus(200);
// } catch (err) {
// console.log(err);
// res.sendStatus(400);
// }
// } else {
// res.sendStatus(400);
// }


This is the only place where I use console.log()! This is the simple sample project in which I able to reproduce the behavior. So why does the code runs twice and WHY my params.myID became favicon.ico?










share|improve this question













I'm working with express and node.js application. I have a regular router, which:




  • finds myID in DB,

  • if myID exists it tries to addVisit()

  • if error occures (may such table doesn't exist) it catches the error, creates the new table and addVisit() to it.


The router code is below:



    router.get('/:myId', errorHandler(async (req, res, next) => {

console.log(req.params.myId + ' This is myID Params!');

const Domain = DomainModel(db, Sequelize);
const Click = ClickModel(db, `${req.params.myId}_clicks`, Sequelize);

try {
let row = await Domain.findOne({ where: { myId: req.params.myId } });

console.log(row.myId + ' This is myID from DB');

if (row.myId) {
try {
await addVisit(Click, req);
res.sendStatus(200);
} catch (err) {
console.log(`This error fires!`);
if (err.message !== `Validation error`) {
try {
await db.sync();
await addVisit(Click, req);
res.sendStatus(200);
} catch (err) {
console.log(err);
res.sendStatus(400);
}
} else {
res.sendStatus(400);
}
}
} else {
console.log(`No such myId in use`);
res.sendStatus(400);
}
} catch (err) {
console.log(err);
}
})


But the code runs twice! My console.log() shows:



1. ==> 1231231231 This is myID Params!
2. ==> 1231231231 This is myID from DB
3. ==> This error fires!
4. ==> favicon.ico This is myID Params!
5. ==> TypeError: Cannot read property 'myID' of null


If I comment this part of code it runs only one time!



// if (err.message !== `Validation error`) {
// try {
// await db.sync();
// await addVisit(Click, req);
// res.sendStatus(200);
// } catch (err) {
// console.log(err);
// res.sendStatus(400);
// }
// } else {
// res.sendStatus(400);
// }


This is the only place where I use console.log()! This is the simple sample project in which I able to reproduce the behavior. So why does the code runs twice and WHY my params.myID became favicon.ico?







javascript node.js express async-await sequelize.js






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 2 days ago









Nastro

1339




1339








  • 1




    Because your browser is sending two requests.
    – tkausl
    2 days ago














  • 1




    Because your browser is sending two requests.
    – tkausl
    2 days ago








1




1




Because your browser is sending two requests.
– tkausl
2 days ago




Because your browser is sending two requests.
– tkausl
2 days ago












2 Answers
2






active

oldest

votes

















up vote
4
down vote



accepted










Whenever you open a webpage, there is a small icon in the upper left corner of the tab, containing the logo of the page. That icon gets loaded from theserver/favicon.ico, if that returns an error the icon stays empty, otherwise the photo returned by that is used as the icon. There are other such reserved files, such as norobots.txt and manifest.json. Therefore it is a bad idea to have the variable url part at the main level. This one:



 router.get('/:myId'


catches everything. Instead you should move it to a subpath:



 router.get('/id/:myId'





share|improve this answer





















  • OMG! How much time I lose with this (( Thank you for explanation. Now it works like it should!
    – Nastro
    2 days ago


















up vote
2
down vote













Because with route param /:myId you will serve /favicon request too. So those are the 2 requests.






share|improve this answer





















  • What should I do to serv only one request?
    – Nastro
    2 days ago






  • 1




    It is bad a practice to use param in the first place. Because you will serve every request. You should always start your route with static part. /static-part/:my-param Or you can validate your url/param with some RegExp, but that is very expensive.
    – lependu
    2 days ago













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',
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%2f53238192%2fwhy-does-async-await-function-run-twice%23new-answer', 'question_page');
}
);

Post as a guest
































2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
4
down vote



accepted










Whenever you open a webpage, there is a small icon in the upper left corner of the tab, containing the logo of the page. That icon gets loaded from theserver/favicon.ico, if that returns an error the icon stays empty, otherwise the photo returned by that is used as the icon. There are other such reserved files, such as norobots.txt and manifest.json. Therefore it is a bad idea to have the variable url part at the main level. This one:



 router.get('/:myId'


catches everything. Instead you should move it to a subpath:



 router.get('/id/:myId'





share|improve this answer





















  • OMG! How much time I lose with this (( Thank you for explanation. Now it works like it should!
    – Nastro
    2 days ago















up vote
4
down vote



accepted










Whenever you open a webpage, there is a small icon in the upper left corner of the tab, containing the logo of the page. That icon gets loaded from theserver/favicon.ico, if that returns an error the icon stays empty, otherwise the photo returned by that is used as the icon. There are other such reserved files, such as norobots.txt and manifest.json. Therefore it is a bad idea to have the variable url part at the main level. This one:



 router.get('/:myId'


catches everything. Instead you should move it to a subpath:



 router.get('/id/:myId'





share|improve this answer





















  • OMG! How much time I lose with this (( Thank you for explanation. Now it works like it should!
    – Nastro
    2 days ago













up vote
4
down vote



accepted







up vote
4
down vote



accepted






Whenever you open a webpage, there is a small icon in the upper left corner of the tab, containing the logo of the page. That icon gets loaded from theserver/favicon.ico, if that returns an error the icon stays empty, otherwise the photo returned by that is used as the icon. There are other such reserved files, such as norobots.txt and manifest.json. Therefore it is a bad idea to have the variable url part at the main level. This one:



 router.get('/:myId'


catches everything. Instead you should move it to a subpath:



 router.get('/id/:myId'





share|improve this answer












Whenever you open a webpage, there is a small icon in the upper left corner of the tab, containing the logo of the page. That icon gets loaded from theserver/favicon.ico, if that returns an error the icon stays empty, otherwise the photo returned by that is used as the icon. There are other such reserved files, such as norobots.txt and manifest.json. Therefore it is a bad idea to have the variable url part at the main level. This one:



 router.get('/:myId'


catches everything. Instead you should move it to a subpath:



 router.get('/id/:myId'






share|improve this answer












share|improve this answer



share|improve this answer










answered 2 days ago









Jonas Wilms

51.6k42344




51.6k42344












  • OMG! How much time I lose with this (( Thank you for explanation. Now it works like it should!
    – Nastro
    2 days ago


















  • OMG! How much time I lose with this (( Thank you for explanation. Now it works like it should!
    – Nastro
    2 days ago
















OMG! How much time I lose with this (( Thank you for explanation. Now it works like it should!
– Nastro
2 days ago




OMG! How much time I lose with this (( Thank you for explanation. Now it works like it should!
– Nastro
2 days ago












up vote
2
down vote













Because with route param /:myId you will serve /favicon request too. So those are the 2 requests.






share|improve this answer





















  • What should I do to serv only one request?
    – Nastro
    2 days ago






  • 1




    It is bad a practice to use param in the first place. Because you will serve every request. You should always start your route with static part. /static-part/:my-param Or you can validate your url/param with some RegExp, but that is very expensive.
    – lependu
    2 days ago

















up vote
2
down vote













Because with route param /:myId you will serve /favicon request too. So those are the 2 requests.






share|improve this answer





















  • What should I do to serv only one request?
    – Nastro
    2 days ago






  • 1




    It is bad a practice to use param in the first place. Because you will serve every request. You should always start your route with static part. /static-part/:my-param Or you can validate your url/param with some RegExp, but that is very expensive.
    – lependu
    2 days ago















up vote
2
down vote










up vote
2
down vote









Because with route param /:myId you will serve /favicon request too. So those are the 2 requests.






share|improve this answer












Because with route param /:myId you will serve /favicon request too. So those are the 2 requests.







share|improve this answer












share|improve this answer



share|improve this answer










answered 2 days ago









lependu

329110




329110












  • What should I do to serv only one request?
    – Nastro
    2 days ago






  • 1




    It is bad a practice to use param in the first place. Because you will serve every request. You should always start your route with static part. /static-part/:my-param Or you can validate your url/param with some RegExp, but that is very expensive.
    – lependu
    2 days ago




















  • What should I do to serv only one request?
    – Nastro
    2 days ago






  • 1




    It is bad a practice to use param in the first place. Because you will serve every request. You should always start your route with static part. /static-part/:my-param Or you can validate your url/param with some RegExp, but that is very expensive.
    – lependu
    2 days ago


















What should I do to serv only one request?
– Nastro
2 days ago




What should I do to serv only one request?
– Nastro
2 days ago




1




1




It is bad a practice to use param in the first place. Because you will serve every request. You should always start your route with static part. /static-part/:my-param Or you can validate your url/param with some RegExp, but that is very expensive.
– lependu
2 days ago






It is bad a practice to use param in the first place. Because you will serve every request. You should always start your route with static part. /static-part/:my-param Or you can validate your url/param with some RegExp, but that is very expensive.
– lependu
2 days ago




















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53238192%2fwhy-does-async-await-function-run-twice%23new-answer', 'question_page');
}
);

Post as a guest




















































































Popular posts from this blog

Full-time equivalent

Bicuculline

さくらももこ