【发布时间】:2018-12-28 11:30:04
【问题描述】:
我对 JS/NodeJs 还很陌生,而且我刚刚了解了异步/承诺。我下面的代码运行一个函数两次,即使它不应该。这是代码和输出,突出显示了问题:
async function itemDetails(req, response) {
const item_number = parseInt(req.params.listingID, 10);
const theList = await querying(item_number);
console.log("LIST " + theList);
console.log("item_number " + item_number);
//theList = res.rows[0];
// define context data
const contextData = {
id: theList.id,
title: 'Listing\'s Details',
object: theList.object,
price: theList.price,
image: theList.image,
firstavail: theList.firstavail,
lastavail: theList.lastavail,
delivery: 'Delivery',
};
console.log(contextData);
return response.render('item_details', contextData);
}
async function querying(code2) {
const listID = await listIdentification(code2);
return new Promise(resolve => {
pool.query('SELECT * FROM listings WHERE id = $1;', [listID], (err, res) =>
{
if (err) {
throw err;
} else {
const theList = res.rows[0];
resolve(theList);
}
});
});
}
async function listIdentification(code) {
return new Promise((resolve, reject) => {
try {
const listingID = parseInt(code, 10);
console.log("check " + typeof(listingID) + listingID );
resolve(listingID);
} catch (error)
{
reject(error);
}
});
}
支票号码36
LIST [对象对象]
item_number 36
{ id: 36, title: 'Listing's Details', object: 'aNYTHIGN',
价格:2,图片:'asd.jpg',firstavail:'2018-01-01',lastavail: '2019-02-02',交货:'交货'}检查 numberNaN //
为什么又跑了?它再次调用函数listIdentification,我不知道为什么。
【问题讨论】:
-
何时/如何调用
itemDetails?请分享所有相关代码。 -
@Jeto itemDetails 在 GET 请求时被调用。不确定它是否相关,但调用者是:app.get('/listing/:listingID', indexControllers.itemDetails);
-
如果我通过手动调用
itemDetails来运行此代码,我只会得到该号码的一个日志。发生这种情况时添加console.trace()调用,以查看调用方式/原因。 -
@Jeto 那是因为我的代码从分贝查询。我确实尝试了console.trace,但它没有显示再次调用该函数的内容:/
-
一些格式是有序的。