簡體   English   中英

我從2個數據庫請求數據。 如何將代碼合並到一個函數中?

[英]I have request data from 2 database. How can I merge code to one function?

我從2個數據庫請求數據。 但是我需要在一個函數中合並2個請求並將數據發送到result.html

function showResult(req, res){
        var n = req.query.query
        mysql_conn.query('SELECT query_text FROM catalogsearch_query WHERE query_text LIKE "%' + n + '%" ORDER BY popularity DESC LIMIT 0 , 10', function(error, rows) {
        res.render('result.html',{result:n , related: rows.map(row => row.query_text)})
    })
}

需要與此代碼合並

mysql_crawl.query('SELECT prod_name, full_price, discount_price, quantity, prod_link, images, prod_desc, status FROM `catalogsearch_fulltext` WHERE MATCH(data_index) AGAINST("cream") LIMIT 0 , 10', function(error, product_data){
res.render('result.html',{product_data: product_data})

如何在一個函數中將代碼合並在一起?

因為它是異步的,所以我們必須等待直到兩個響應都執行完render (如果mysql模塊支持promise,則可以使用另一種方法 。)。

var n = req.query.query;
mysql_conn.query('SELECT query_text FROM catalogsearch_query WHERE query_text LIKE "%' + n + '%" ORDER BY popularity DESC LIMIT 0 , 10', function (error, rows) {

    // at this point, only the first query has been executed

    mysql_crawl.query('SELECT prod_name, full_price, discount_price, quantity, prod_link, images, prod_desc, status FROM `catalogsearch_fulltext` WHERE MATCH(data_index) AGAINST("cream") LIMIT 0 , 10', function(error, product_data) {

        // at this point, both queries should have been executed

        res.render('result.html', {
           result: n, 
           related: rows.map(row => row.query_text),
           product_data: product_data
        })
    });
});

我從未使用過此模塊,但要小心SQL注入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM