簡體   English   中英

如何處理node.js承諾鏈中的錯誤並解析promises數組

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

我正在嘗試正確處理下面node.js函數的錯誤/異常,而不會影響其(a)同步執行。

具體來說,我想確保在開始根據sql語句創建新數據之前完全清除數據庫(“removeCustomer”)。

問題:我需要通過helper.returnAPISuccess('成功插入行',對,回調)來解決promises ...

但是,如果我將.then ()鏈接pairs.map()函數,它會與整體同步混淆 ,例如,只返回第一行而不是.map創建的每個結果。

也許我可以嘗試Promise.all()? 我想我需要將所有“對”添加到一組promises中 ,解決所有這些,然后.then(helper.returnAPISuccess ......等等?或者我應該嘗試展平嵌套的promises ......?

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

任何幫助將非常感謝,謝謝:)

助手:

removeRecipient:

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

也許我可以嘗試Promise.all()? 我想我需要將所有“對”添加到一組promises中,解決所有這些,然后.then(helper.returnAPISuccess ......等等?

是的,這是可行的方式。

或者我應該嘗試壓扁嵌套的承諾......?

你也應該這樣做。 也許更重要的是,最好不要調用任何callback參數,而是從updateCustomer返回一個promise。

暫無
暫無

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

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