I am newbie in node.js. I am trying to do something like this -
I have created one Add To Cart API where i am first checking whether session cart exist or not. If not exist, i am creating new cart via getCartCode(res)
method.
app.post('/addToCart', function(req, res) {
console.log('[POST] /addToCart');
var cart = req.body.conversation.memory['cart'];
if(!cart) {
const response = getCartCode(res);
console.log("******* Result ************ : " + response.conversation.memory['cart']); // Giving undefined exception here
}
}
getCartCode - This method create cart and return the code which i am returning via res.json
function getCartCode(res) {
return createCart()
.then(function(result) {
res.json({
conversation: {
memory: {
'cart': result,
}
}
});
return result;
})
.catch(function(err) {
console.error('productApi::createCart error: ', err);
});
}
Now what i want is, i want to get cart code in addToCart API in response. I am trying to print cart code in console.log, but it's not printing anything and throwing exception.
First, you're trying to call a function that returns a
Promise
, which is asynchronous, and expect it to behave as if it was synchronous, which is not going to work:You'd have to use something like
async/await
if you want to be able to usegetCartCode
similarly to what you're doing right now, like so:Second, don't pass
res
to thecreateCart
function. Instead, get the data you need from thecreateCart
function and callres.json
inside the/addToCart
controller.Here's how you have to handle this: