簡體   English   中英

function 調用 ASYNC/AWAIT

[英]function call with ASYNC/AWAIT

我確定這個問題是由於我缺乏異步/等待知識。 但是,我無法弄清楚我做錯了什么。 最終目標是 addSupplier() 進程等待 getSupplier() function 完成處理,直到它繼續。

背景信息:這是使用 HTML、JS 和 Postgres 的更大的 Electron 應用程序的內部。 這段代碼正在處理來自 HTML 表單的請求,將供應商插入表中,然后刷新位於同一頁面上的 HTML 表。 HTML 代碼未顯示,但如果需要我可以包含。

當前代碼 - 未拆分為單獨的函數 - 按需要工作:

function addSupplier(){
  const connString = getConnData();
  const client = new Pool(connString)
  client.connectionTimeoutMillis = 4000;

  var supplierID = document.getElementById("dbSupplierID").value;
  var supplierName = document.getElementById("dbSupplierName").value;
  var supplierUnit = document.getElementById("dbSupplierUnit").value;

  const supplier_insert_query = {
    text: "INSERT INTO suppliers(supplier_id, company, unit)VALUES('"+ supplierID +"', '"+ supplierName +"', '"+ supplierUnit +"')",
  }

  const supplier_select_query = {
    text: "SELECT supplier_id AS id, company, unit FROM suppliers",
    rowMode: 'array',
  }

  // Connect to client, catch any error. 
  client.connect()
  .then(() => console.log("Connected Successfuly"))
  .catch(e => console.log("Error Connecting"))
  .then(() => client.query(supplier_insert_query))
  .catch((error) => alert(error))
  .then( () => { // After inserting new author, run author query and refresh table. 
    client.query(supplier_select_query)
    .then(results => {
      // Create the static header for the table
      var table = ""; table_head = ""
      for (i=0; i<results.fields.length; i++) { if (i==3) {continue}
        table_head += '<th>' + results.fields[i].name + '</th>'
      }

      // Create the body of the table
      for (j=0; j<results.rows.length; j++) { //j: rows, k: columns
        results.rows[-1] = []
        if (results.rows[j][0] == results.rows[j-1][0]) {continue}
        table += '<tr>'
        for (k=0; k<results.fields.length; k++) { if (k==3) {continue} // Skip creating the last column of this query. This data is only used to add information to the first column.
          if (k==0) { // When you've reached a session_id cell, write the names of the tests in this session in that cell
            var x=0; x = j; var tests = ''
            while (results.rows.length > x && results.rows[x][0] == results.rows[j][0]) {
             tests += '<br>' + (results.rows[x][3]==null ? '':results.rows[x][3]); x++
            }
          }
          table += `<td>${results.rows[j][k]}` + (k==0 ? `${tests}`:``) + '</td>'
        }
        table += '</tr>'
      }

      // Grab the constructed HTML strings and write them to the document to create the table there
      document.getElementById('supplier_table_head').innerHTML = ""
      document.getElementById('supplier_table').innerHTML = ""

      document.getElementById('supplier_table_head').innerHTML += table_head
      document.getElementById('supplier_table').innerHTML += table
    }).catch(e => console.error("ERROR in supplier table query\n",e.stack))
  })
    
  // Clearing input fields.
  document.getElementById('dbSupplierID').value = ""
  document.getElementById('dbSupplierName').value = ""
  document.getElementById('dbSupplierUnit').value = ""

  // Preventing app refresh
  event.preventDefault()
  
  .finally(() => client.end())
}

編輯:我進行了異步更改,它似乎正確調用了 function 但 function 沒有處理。 這就是我現在所擁有的。 如果我發出警報,它會處理警報“TypeError:Promise resolver undefined is not a function”,然后退出並刷新整個應用程序。

// Function to add a supplier to the DB
async function addSupplier(){
  const connString = getConnData();
  const client = new Pool(connString)
  client.connectionTimeoutMillis = 4000;

  var supplierID = document.getElementById("dbSupplierID").value;
  var supplierName = document.getElementById("dbSupplierName").value;
  var supplierUnit = document.getElementById("dbSupplierUnit").value;

  const supplier_insert_query = {
    text: "INSERT INTO suppliers(supplier_id, company, unit)VALUES('"+ supplierID +"', '"+ supplierName +"', '"+ supplierUnit +"')",
  }

  // Connect to client, catch any error. 
  client.connect()
  .then(() => console.log("Connected Successfuly")) // Connection is good
  .catch(e => console.log("Error Connecting"))      // CATCH - Connect error
  .then(() => client.query(supplier_insert_query))  // Run supplier insertion query
  .catch((error) => alert(error))                   // CATCH - error in insertion query
  .then(async () => {
    // wait for getSuppliers function to execute
    await getSuppliers();
  }) 
  .then(() => {
    // Clearing input fields.
    document.getElementById('dbSupplierID').value = ""
    document.getElementById('dbSupplierName').value = ""
    document.getElementById('dbSupplierUnit').value = ""

    // Preventing app refresh
    event.preventDefault()
  })
  .catch(e => console.error("ERROR in supplier table query\n",e.stack)) //Catch any error from getSuppliers
  .finally(() => client.end())                      // Close the connection
}

async function getSuppliers(){
  let promise = new Promise()
  // Query to pull all Suppliers info from database
  const supplier_select_query = {
    text: "SELECT supplier_id AS id, company, unit FROM suppliers",
    rowMode: 'array',
  }

  // Query the database and pull the results into the HTML table
  client.query(supplier_select_query)
    .then(results => {
      // Create the static header for the table
      var table = ""; table_head = ""
      for (i=0; i<results.fields.length; i++) { if (i==3) {continue}
        table_head += '<th>' + results.fields[i].name + '</th>'
      }

      // Create the body of the table
      for (j=0; j<results.rows.length; j++) { //j: rows, k: columns
        results.rows[-1] = []
        if (results.rows[j][0] == results.rows[j-1][0]) {continue}
        table += '<tr>'
        for (k=0; k<results.fields.length; k++) { if (k==3) {continue} // Skip creating the last column of this query. This data is only used to add information to the first column.
          if (k==0) { // When you've reached a session_id cell, write the names of the tests in this session in that cell
            var x=0; x = j; var tests = ''
            while (results.rows.length > x && results.rows[x][0] == results.rows[j][0]) {
             tests += '<br>' + (results.rows[x][3]==null ? '':results.rows[x][3]); x++
            }
          }
          table += `<td>${results.rows[j][k]}` + (k==0 ? `${tests}`:``) + '</td>'
        }
        table += '</tr>'
      }

      // Grab the constructed HTML strings and write them to the document to create the table there
      document.getElementById('supplier_table_head').innerHTML = ""
      document.getElementById('supplier_table').innerHTML = ""

      document.getElementById('supplier_table_head').innerHTML += table_head
      document.getElementById('supplier_table').innerHTML += table
    })
  .finally(() => {return promise.resolve()})
}

您需要在 function 聲明前加上async關鍵字才能在其中使用await關鍵字。


client.connect()
  .then(() => console.log("Connected Successfuly")) // Connection is good
  .catch(e => console.log("Error Connecting"))      // CATCH - Connect error
  .then(() => client.query(supplier_insert_query))  // Run supplier insertion query
  .catch((error) => alert(error))                   // CATCH - error in insertion query
  .then(async () => {
    // wait for getSuppliers function to execute
    await getSuppliers()

    // Clearing input fields.
    document.getElementById('dbSupplierID').value = ""
    document.getElementById('dbSupplierName').value = ""
    document.getElementById('dbSupplierUnit').value = ""

    // Preventing app refresh
    event.preventDefault()
  }) 

await關鍵字等待 promise 在運行代碼之前被解析( 在 Javascript 中等待)。 您還沒有讓getSuppliers創建或解析 promise,所以 await 不會在這里等待任何東西。 我自己對創建和解決承諾不是很熟悉,但是像promise = new Promise()getSuppliers開頭並在最后return promise.resolve()這樣的東西應該可以正常工作。

編輯:在箭頭 function 和await getSuppliers()之前,您似乎也缺少async ,這也可能導致問題。 我可能已經假設承諾是問題所在,因為await關鍵字確實會嘗試將任何不是 promise 的東西轉換為已解決的問題,但我不熟悉它應該如何始終如一地工作。

暫無
暫無

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

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