简体   繁体   English

javascript代码从执行中跳过了几行

[英]javascript code skips some lines from executing

What i want to achieve is, inserting text values from table cells in to 2 different sql table. 我要实现的是,将表单元格中的文本值插入2个不同的sql表中。 They work if i comment the other one. 如果我评论另一个,它们会起作用。 But if i want to use the code above it's completely missing the first loop where y === 0 and second sql receives all values as undefined but i can print them just fine before sql.connect line. 但是,如果我想使用上面的代码,它会完全丢失第一个循环,其中y === 0,第二个sql接收所有未定义的值,但是我可以在sql.connect行之前将它们打印出来。

Here is my code 这是我的代码

function update() {
  $('body').on('click', '#btnSave', function() {
    values = []
    $('input.form-control').each(function() {
      var valueNew = $(this).val();
      $(this).attr('disabled', true);
      values.push(valueNew);
    })

    for (var y = 0; y < 2; y++) {
      if (y === 0) {
        console.log(y)
        sql.close()
        sql.connect(config, err => {
          const request = new sql.Request()
          let editorTexts = $('#summernote').summernote()[0].value;
          console.log(editorTexts)
          request.query(`INSERT INTO table (col1, col2, col3) VALUES ('${values[1]}', '${values[0]}', '${editorTexts}')`)
          request.on('recordset', columns => {})
          request.on('row', row => {})
          request.on('error', err => {})
          request.on('done', result => {
            console.log(result.rowsAffected)
          })
        })
      } else {
        var table = $("#table tbody");
        for (var x = 0; x < table[0].rows.length; x++) {
          sql.close()
          sql.connect(config, err => {
            const request = new sql.Request()
            request.query(`INSERT INTO table2 (col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14) VALUES ('${values[1]}', '${values[0]}', '${values[3 + (x*10)]}', '${values[4 + (x*10)]}', '${values[5 + (x*10)]}', '${values[6 + (x*10)]}', '${values[7 + (x*10)]}' ,'${values[8 + (x*10)]}','${values[9 + (x*10)]}', '${values[10 + (x*10)]}', '${values[2]}', '${values[11 + (x*10)]}', '${values[12 + (x*10)]}', '${+lastID[0]+1}')`)
            request.on('recordset', columns => {})
            request.on('row', row => {})
            request.on('error', err => {})
            request.on('done', result => {
              console.log(result.rowsAffected)
            })
          })
        }
      }
    }
  })
}

No, the code is still running, but in asynchronous. 不,代码仍在运行,但是是异步的。 Asynchronous code takes statements outside of the main program flow, allowing the code after the asynchronous call to be executed immediately without waiting. 异步代码将语句带到主程序流之外,从而允许异步调用后的代码立即执行而无需等待。

Because sql function is async, you closed the connection before the first loop was done. 因为sql函数是异步的,所以在完成第一个循环之前就关闭了连接。 Eg, when y === 1 , the process of insertion when y === 0 still running, and you close it, so the transaction was canceled.It's better for you to learn more about how asynchronous, callback, promise works 例如,当y === 1 ,当y === 0时插入过程仍在运行,并且您将其关闭,因此事务被取消了。最好让您更多地了解异步,回调,promise如何工作

I don't know whether your sql client supported pooling or not. 我不知道您的sql客户端是否支持池。 However, you should remove the line sql.close() . 但是,您应该删除sql.close() Closed it once after all transaction are done. 完成所有交易后将其关闭一次。

However, what I am concerning is, if y has only 0 and 1 , why do you do it in loop? 但是,我所关心的是,如果y只有01 ,为什么要循环执行呢? It is better if you do it step by step like this: 最好按如下步骤进行:

function update() {
  $('body').on('click', '#btnSave', function() {
    values = []
    $('input.form-control').each(function() {
      var valueNew = $(this).val();
      $(this).attr('disabled', true);
      values.push(valueNew);
    })

    // y === 0
    sql.connect(config, err => {
      const request = new sql.Request()
      let editorTexts = $('#summernote').summernote()[0].value;
      console.log(editorTexts)
      request.query(`INSERT INTO table (col1, col2, col3) VALUES ('${values[1]}', '${values[0]}', '${editorTexts}')`)
      request.on('recordset', columns => {})
      request.on('row', row => {})
      request.on('error', err => {})
      request.on('done', result => {

         // y === 1
         var table = $("#table tbody");
          for (var x = 0; x < table[0].rows.length; x++) {
            sql.connect(config, err => {
              const request = new sql.Request()
              request.query(`INSERT INTO table2 (col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14) VALUES ('${values[1]}', '${values[0]}', '${values[3 + (x*10)]}', '${values[4 + (x*10)]}', '${values[5 + (x*10)]}', '${values[6 + (x*10)]}', '${values[7 + (x*10)]}' ,'${values[8 + (x*10)]}','${values[9 + (x*10)]}', '${values[10 + (x*10)]}', '${values[2]}', '${values[11 + (x*10)]}', '${values[12 + (x*10)]}', '${+lastID[0]+1}')`)
              request.on('recordset', columns => {})
              request.on('row', row => {})
              request.on('error', err => {})
              request.on('done', result => {
                console.log(result.rowsAffected)
              })
            })
          }
        })
      })
    }
  })
}

If you know how to work with Promise , it's better to wrap async task with Promise. 如果您知道如何使用Promise ,则最好用Promise包装异步任务。 It's safer and cleaner in code, like this: 在代码中更安全,更清洁,如下所示:

    function insertTable(values) {
      return sql.connect(config)
        .then((pool) => {
          const editorTexts = $('#summernote').summernote()[0].value

          return pool.request().query(`INSERT INTO table (col1, col2, col3) VALUES ('${values[1]}', '${values[0]}', '${editorTexts}')`)
        })
    }

    function insertTable1(x, values) {
      return sql.connect(config)
        .then((pool) => {
          return pool.request().query(`INSERT INTO table2 (col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14) VALUES ('${values[1]}', '${values[0]}', '${values[3 + (x*10)]}', '${values[4 + (x*10)]}', '${values[5 + (x*10)]}', '${values[6 + (x*10)]}', '${values[7 + (x*10)]}' ,'${values[8 + (x*10)]}','${values[9 + (x*10)]}', '${values[10 + (x*10)]}', '${values[2]}', '${values[11 + (x*10)]}', '${values[12 + (x*10)]}', '${+lastID[0]+1}')`)
      })
        })
    }

    function update() {
      $('body').on('click', '#btnSave', function() {
        const values = []
        $('input.form-control').each(function() {
          var valueNew = $(this).val();
          $(this).attr('disabled', true);
          values.push(valueNew);
        })

        // y === 0
        insertTable(values)
          .then(() => {
            // y === 1
            const table = $("#table tbody");
            const tasks = []
              for (var x = 0; x < table[0].rows.length; x++) {
                tasks.push(insertTable1(x, values));
              }

              return Promise.all(tasks);
          }).then((results) => {
            console.log("Inserted successfully");
          }).catch((err) => {
            console.error(err);
          });
      })
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM