【问题标题】:Javascript/async function being called twice, returning error on the second turnJavascript/async 函数被调用两次,第二次返回错误
【发布时间】: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,但它没有显示再次调用该函数的内容:/
  • 一些格式是有序的。

标签: javascript asynchronous


【解决方案1】:

我发现了问题所在,以防其他人发现同样的问题。事实上,这是一个问题

image: theList.image

每当数据库的 URL 无效时,我都会收到此错误。我所要做的就是在分配给数组之前执行一个验证,所以我添加了以下内容:

var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

if (!pattern.test(theList.image))
    {
          theList.image="";
    }

现在如果 URL 无效,theList.image 将有一个空字符串。随着这种变化,问题不再发生。不过,我仍然不知道为什么它被调用了两次并出现该错误。

【讨论】:

  • 假设itemDetails是一个服务器端函数,错误可能导致客户端再次请求。
猜你喜欢
  • 2021-12-06
  • 2013-07-02
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多