首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用ASYNC/AWAIT进行函数调用

使用ASYNC/AWAIT进行函数调用
EN

Stack Overflow用户
提问于 2020-07-22 02:54:21
回答 2查看 57关注 0票数 0

我确信这个问题是因为我缺乏异步/等待知识。然而,我不知道我做错了什么。最终目标是让addSupplier()进程等待getSuppliers()函数完成处理,直到它继续。

背景信息:这是一个使用HTML、JS和Postgres的更大的电子应用程序。这段代码处理来自HTML表单的请求,请求将一个供应商插入到表中,然后刷新位于同一页面上的HTML表。HTML代码没有显示,但我可以包括如果需要。

当前代码-没有拆分成单独的函数-按预期工作:

代码语言:javascript
运行
复制
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())
}

编辑:我进行了异步更改,它似乎正确地调用了函数,但函数无法处理。这就是我现在拥有的。如果我抛出一个警告,它会处理警告'TypeError: Promise resolver undefined is not a function‘,然后踢出并刷新整个应用程序。

代码语言:javascript
运行
复制
// 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()})
}
EN

回答 2

Stack Overflow用户

发布于 2020-07-22 03:12:10

要在函数声明中使用async关键字,需要在函数声明前加上await关键字。

代码语言:javascript
运行
复制
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()
  }) 
票数 0
EN

Stack Overflow用户

发布于 2020-07-22 03:13:18

在运行后面的代码(await in Javascript)之前,await关键字等待promise被解析。您还没有让getSuppliers创建或解析promise,所以await在这里不会等待任何东西。我自己对创建和解析promises不是很熟悉,但是像getSuppliers开头的promise = new Promise()和结尾的return promise.resolve()这样的东西应该可以正常工作。

编辑:在使用await getSuppliers()的箭头函数之前,似乎还缺少一个async,这也可能导致问题。我可能会草率地假设promises是问题所在,因为await关键字确实会尝试将任何不是promise的内容转换为已解决的promise,但我并不熟悉这种方式的一致性。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63021257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档