简体   繁体   English

如何处理node.js承诺链中的错误并解析promises数组

[英]How to handle errors in node.js promise chain and resolve array of promises

I'm trying to properly handle errors/exceptions for the node.js function below without affecting its (a)synchronous execution. 我正在尝试正确处理下面node.js函数的错误/异常,而不会影响其(a)同步执行。

Specifically, I want to make sure that the database is completely cleared ("removeCustomer") before beginning to create new data per the sql statements. 具体来说,我想确保在开始根据sql语句创建新数据之前完全清除数据库(“removeCustomer”)。

Issue: I need to resolve promises via helper.returnAPISuccess('Successfully inserted rows', pairs, callback) somewhere... 问题:我需要通过helper.returnAPISuccess('成功插入行',对,回调)来解决promises ...

However if I chain .then() to the pairs.map() function, it messes with the overall synchrony , eg only the first row is returned instead of each result created by .map. 但是,如果我将.then ()链接pairs.map()函数,它会与整体同步混淆 ,例如,只返回第一行而不是.map创建的每个结果。

Maybe I could try Promise.all()? 也许我可以尝试Promise.all()? I think I need to add all "pairs" to an array of promises , resolve them all, and .then(helper.returnAPISuccess... etc.? Or should I try to flatten the nested promises...? 我想我需要将所有“对”添加到一组promises中 ,解决所有这些,然后.then(helper.returnAPISuccess ......等等?或者我应该尝试展平嵌套的promises ......?

updateCustomer function: 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);
    });
}

Any help would be hugely appreciated, thanks :) 任何帮助将非常感谢,谢谢:)

Helpers: 助手:

removeRecipient: removeRecipient:

module.exports.removeRecipient = (db, email) => {
  let sql = `DELETE FROM purchases_table WHERE email_address=$1`;
  return db.queries.result(sql, [email]);
}

returnAPISuccess: 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);
}

Maybe I could try Promise.all()? 也许我可以尝试Promise.all()? I think I need to add all "pairs" to an array of promises, resolve them all, and .then(helper.returnAPISuccess... etc.? 我想我需要将所有“对”添加到一组promises中,解决所有这些,然后.then(helper.returnAPISuccess ......等等?

Yes, that's exaclty the way to go. 是的,这是可行的方式。

Or should I try to flatten the nested promises...? 或者我应该尝试压扁嵌套的承诺......?

You should do that as well. 你也应该这样做。 And maybe more importantly, it would be a good practice not to call any callback parameter at all, but instead to return a promise from updateCustomer . 也许更重要的是,最好不要调用任何callback参数,而是从updateCustomer返回一个promise。

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

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