[英]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.