As a newcomer to the world of await, I'm struggling to handle errors and rejections properly. The unhandled rejections from the shopify-api.js function keep cropping up, and I can't seem to print all the errors that are coming from my middleware in index.js.
Is there a correct way to handle awaits? How can I ensure that all errors are printed?
index.js
const functions = require('firebase-functions');
const app = require('express')();
const cors = require('cors');
// Handling cross-origin requests
app.use(cors({ origin: true }));
const asyncMiddleware = fn => (req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch(err => {
console.error(err);
res.json(err)
})
.catch(next)
};
app.get('/v1/Test/Shopify', asyncMiddleware( async (req, res, next) => {
req.params.workshopId = "TEST_CR"
req.params.date = "2018-11-30"
req.params.startTime = "11:00"
let result1 = await ShopifyWorkshop.AddDate(req, res, next)
console.log("ShopifyWorkshop.AddDate: Success" .green)
res.status(200).json({message: "Success"})
}));
exports.AddDate = async (req, res, next) => {
await Helper.CheckParamsIsNull(req.params)
let wsId = req.params.workshopId
let wsDate = req.params.date
let wsTime = req.params.startTime
// Check if workshop is a level
if (Helper.IsWorkshopType(wsId)) {
return await Promise.all(WORKSHOP_TYPE[wsId].levelNames.map( async (typeName) => {
WORKSHOP_CATEGORY[typeName].codeNames.map( async (codeName) => {
for (let wsId in WORKSHOP_INFO) {
if (WORKSHOP_INFO[wsId].codeName === codeName) {
addVariant(wsId, wsDate, wsTime)
}
}
})
}))
} else if (Helper.IsWorkshopCategory(wsId)) {
return await Promise.all(WORKSHOP_CATEGORY[wsId].codeNames.map ( async (codeName) => {
for (let wsId in WORKSHOP_INFO) {
if (WORKSHOP_INFO[wsId].codeName === codeName) {
await addVariant(wsId, wsDate, wsTime)
}
}
}))
} else {
return await addVariant(wsId, wsDate, wsTime)
}
}
shopify-api.js
exports.AddAProductVariant = async (id, options) => {
console.log("Adding variant to product..." + options.option1)
let result = await shopify.productVariant.create(id, options)
console.log("Added product variant: " + options.option1)
return result
}