forEach函数的多个promise

时间:2018-08-06 10:59:50

标签: node.js

我基本上想要的是循环一个诺言,以便我可以输出和排列结果。

  var oracle_table = new oracle_driver(tableName);

  var promise = new Promise(queryObject, function(resolve, reject) {
    oracle_table.query(queryObject, (err, result) => {
      if(err){
        reject(err);
      }
      resolve(result);
    });
  })

  Promise.all(vals.forEach((queryObject) => promise(queryObject)))
    .then((results) => {
      // results expected to be [result, result, result] from var promise
      res.status(200).json(results)
    })
    .catch((err) => {
      res.status(500).send(err)
    })

oracle_driver是连接到数据库的类。

tableName是正在编辑的表的名称。

.query是一个获取对象,对其进行转换并查询返回结果的数据库的函数。以下是.query的代码:

    // query
  query(queryObject, callback) {
    queryObject = JSON.parse(queryObject) // Make sure that the object is in JSON format
    let table = this.tableName; // decaring the name of the table from the constructor
    let query = `SELECT * FROM ${table} WHERE `; // declaring the beginning query
    // Splitting the data from the object in arrays of there keys and there values
    let keys = Object.keys(queryObject);
    var values = Object.keys(queryObject).map(function(key) {
      return queryObject[key];
    });
    let frist = true;
    // constructing the two new arrays into a string
    for (var i = 0; i < keys.length; i++) {
      if (!frist) query = query.concat(`AND (${keys[i]} = '${values[i]}')`)
      else query = query.concat(`(${keys[i]} = '${values[i]}')`)
      frist = false;
    }
    // Showing the query
    console.log('query'+query);
    console.log('connecting to db');
    // Get a non-pooled connection
    oracledb.getConnection(
      databaseDetails, // DB connection details
      function(err, connection) {
        if (err) {
          console.error(err.message);
          return;
        }
        connection.execute(query,
          {

          },
          function(err, result) {
            if(err) console.error(err.message);
            console.log('results from db driver ----');
            console.log(result.rows);
            callback(err, result.rows); // Callback with db details 
            doRelease(connection); // close connection
          }
        );
      }
    );
  }

1 个答案:

答案 0 :(得分:0)

首先,您需要将Promise包装到一个函数中,以便可以向其发送查询。

第二,您需要使用SELECT COUNT(*) FROM ( SELECT id , car_no , CASE WHEN car_no = 0 THEN @i:=@i+1 ELSE @i:=0 END i FROM my_table , (SELECT @i:=0) vars ORDER BY id ) x WHERE i = 3 而不是map,因为您需要向forEach提供Promises列表,而不仅仅是在此处调用函数。

这是应该起作用的最终答案:

Promise.all