如何在节点js中为数据库应用程序同步编写代码

时间:2019-06-29 10:11:36

标签: javascript node.js

我正在开发一个将城市添加到users_city表的API 以下是发布请求:

import pandas as pd

df = pd.DataFrame({"col1": ["LIQUID PARAFFIN(1.25 MG)+MAGNESIUM HYDROXIDE(300.0 MG)+SODIUM PICOSULFATE(3.33 MG)"]})   # Value to be plotted
print(df.values[0][0])
# LIQUID PARAFFIN(1.25 MG)+MAGNESIUM HYDROXIDE(300.0 MG)+SODIUM PICOSULFATE(3.33 MG)

df.col1 = df.col1.str.replace(r'\([^)]*\)', "")
print(df.values[0][0])
# LIQUID PARAFFIN+MAGNESIUM HYDROXIDE+SODIUM PICOSULFATE

以下是我的代码的输出:

router.post("/users_city_new",function(req,res){
        var cities = req.body.city_id;
        var count = 0;
        var query = ""
        console.log(cities)
        if(req.headers.authorization != secret){
            res.json({"Error" : true, "Message" : "API Key is Missing or is Invalid"});
        }
        else {
          pool.getConnection(function(err, connection) {
          query1 = "DELETE FROM users_city WHERE user_id = "+mysql.escape(req.body.user_id);
          connection.query(query1,function(err,rows){
        if(err){
          console.log(err)
        }
        else{
          console.log("Success")
        }

        for(var i=0; i<cities.length; i++){
            var city = cities[i].city
            console.log(city)
            query = "INSERT INTO users_city (city_id,user_id) VALUES ("+mysql.escape(city)+","+mysql.escape(req.body.user_id)+")";
            connection.query(query,function(err,rows){
                count++
                console.log(count)
            });
       }
       connection.release();

        if(count == cities.length){
            console.log("executed")
            res.json({"Error" : false, "Message": "Inserted Successfully"})
        }
        else{
            console.log("executed")
            res.json({"Error" : true, "Message": "Error Inserting cities", "Count" : count})
        }

      });
  });

  }
});

我想让我的代码按照程序的流程运行。请帮助我解决此问题

预先感谢

1 个答案:

答案 0 :(得分:1)

请检查节点js中的async & await函数。 我已经为您提供了一个简单的示例代码。

router.post("/users_city_new", async function(req, res) { 
   // async function should be declared before awaiting

      let cities = req.body.city_id, count = 0, query = "";

      if(req.headers.authorization != secret){
          res.json({"Error" : true, "Message" : "API Key is Missing or is Invalid"});
      } else {
        try{
          query1 = "DELETE FROM users_city WHERE user_id = " + mysql.escape(req.body.user_id);

          // await function that returns promise
          // this waits until the execution
          let connection = await pool.getConnection();

          // Again 'await' waits until the execution
          let rows = await connection.query(query1);

          for(var i = 0; i < cities.length; i++){
              var city = cities[i].city
              console.log(city)

              query = "INSERT INTO users_city (city_id,user_id) VALUES ("+mysql.escape(city)+","+mysql.escape(req.body.user_id)+")";

              // wait for query to run
              let rows = await connection.query(query);

              // executed only when query runned
              count++;
              console.log(count);
         }

         connection.release();

          if(count == cities.length){
              console.log("executed")
              res.json({"Error" : false, "Message": "Inserted Successfully"})
          } else {
              console.log("executed")
              res.json({"Error" : true, "Message": "Error Inserting cities", "Count" : count})
          }

        }catch(e){
            // handle you are errors here
        }
      }
    })

我相信这会对您有所帮助。