【发布时间】:2019-09-25 05:22:30
【问题描述】:
我正在尝试正确处理以下 node.js 函数的错误/异常,而不影响其 (a) 同步执行。
具体来说,我想确保在开始根据 sql 语句创建新数据之前完全清除数据库(“removeCustomer”)。
问题:我需要在某处通过 helper.returnAPISuccess('Successfully inserted rows', pairs, callback) 解决承诺...
但是,如果我将 .then() 链接到 pairs.map() 函数,它会与整体同步混乱,例如仅返回第一行,而不是 .map 创建的每个结果。
也许我可以试试 Promise.all()?我想我需要将所有“对”添加到一个 promise 数组,将它们全部解决,然后 .then(helper.returnAPISuccess... 等等?或者我应该尝试扁平化嵌套的承诺...?
updateCustomer 函数:
updateCustomer(email, body, callback) {
// Delete old data before creating new data for the customer
helper.removeCustomer(this.db, email, callback)
.then(() => {
// Query to find category/item pairs
let sql =`SELECT key as category, json_array_elements_text(value::json) as item
FROM json_each_text($1:csv)`;
this.db.queries.any(sql, [body])
.then(pairs => {
const insert =`INSERT INTO purchases_table(item, category, email_address)
VALUES($1, $2, $3)`;
// Map each pair to the customer's email and insert into the purchases table
pairs.map(pair => {
this.db.queries.none(insert, [pair['item'], pair['category'], email])
.catch(error => {
helper.returnAPIError(error, 'Error inserting customer data', callback);
});
})
})
.catch(error => {
helper.returnAPIError(error, 'Error retrieving category/item pairs', callback);
});
})
.catch(error => {
helper.returnAPIError(error, 'Error removing old customer data', callback);
});
}
任何帮助将不胜感激,谢谢:)
助手:
删除收件人:
module.exports.removeRecipient = (db, email) => {
let sql = `DELETE FROM purchases_table WHERE email_address=$1`;
return db.queries.result(sql, [email]);
}
returnAPISuccess:
module.exports.returnAPISuccess = (msg, data, callback) => {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
"Content-Type": "application/json",
},
body: JSON.stringify({ message: msg, data: data })
};
callback(null, response);
}
【问题讨论】:
标签: javascript node.js asynchronous error-handling promise