首先,您试图调用一个返回 a 的函数Promise
,它是异步的,并期望它表现得好像它是同步的,但这是行不通的:
// this won't work
const response = getCartCode(res)
function getCartCode(res) {
return createCart().then(function(result) {
return {...}
});
}
async/await
如果您希望能够使用类似于getCartCode
您现在正在做的事情,您必须使用类似的东西,如下所示:
app.post('/addToCart', function(req, res) {
async function handleAddToCart() {
// i suggest you use something like the `lodash.get`
// function to safely access `conversation.memory.cart`
// if one of these attributes is `undefined`, your `/addToCart`
// controller will throw an error
const cart = req.body.conversation.memory.cart
// or, using `lodash.get`
// const cart = _.get(req, 'body.conversation.memory.cart', null)
if (!cart) {
const response = await getCartCode().catch(err => err)
// do whatever you need to do, or just end the response
// and also make sure you check if `response` is an error
res.status(200).json(response)
return
}
// don't forget to handle the `else` case so that your
// request is not hanging
res.status(...).json(...)
}
handleAddToCart()
})
function getCartCode() {
return createCart()
.then(function(result) {
return { conversation: { memory: { cart: result } } }
})
.catch(function(err) {
console.error('productApi::createCart error:', err);
throw err
})
}
其次,不要传递res
给createCart
函数。相反,从createCart
函数中获取您需要的数据并在控制器res.json
内部调用。/addToCart
以下是您必须处理的方法:
app.post('/addToCart', function(req, res) {
const cart = req.body.conversation.memory.cart
if (!cart) {
getCartCode()
.then(function (result) {
res.json(result)
})
.catch(/* handle errors appropriately */)
return;
}
// return whatever is appropriate in the `else` case
res.status(...).json(...);
})
function getCartCode() {
return createCart()
.then(function(result) {
return { conversation: { memory: { cart: result } } }
})
.catch(function(err) {
console.error('productApi::createCart error:', err);
throw err
})
}