我正在尝试创建一个由控制器和路由分隔的nodejs API。我正在尝试在多个集合中查找和更新,然后将它们放入多个promise中以返回单个响应,但是我只得到null
下面在做什么错了?
controller.js
var x = (req, res, next, userID, product) => {
let query = {
uid: userID
}
let update = {
$push: {
product: product,
}
}
let options = {
safe: true,
new: true,
upsert: true
}
Model.findOneAndUpdate(query, update, options).exec()
.then(result => {
return true
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
})
};
module.exports = x;
Route.js
const controller = require('./user-product')
router.post('/api', function (req, res, next) {
var p1 = controller(req, res, next, userID, product)
var allDone = Promise.all([p1])
allDone
.then(function (e) {
res.send(e) //this is null
})
.catch(function (e) {
console.log(e);
})
});
答案 0 :(得分:1)
您没有从控制器功能返回诺言。您只是返回了result
和error
因此,相反,您应该在控制器函数内部返回promise
Route.js
const controller = require('./user-product')
router.post('/api', function (req, res, next) {
var p1 = controller(req, res, next, userID, product)
var allDone = Promise.all([p1])
allDone.then(function (e) {
res.send(e)
})
.catch(function (e) {
console.log(e);
})
})
controller.js
var x = (req, res, next, userID, product) => {
let query = { uid: userID }
let update = { $push: { product: product }}
let options = {
safe: true,
new: true,
upsert: true
}
return Model.findOneAndUpdate(query, update, options).exec()
}
module.exports = x;
使用 async await 语法
可能更容易Route.js
const controller = require('./user-product')
router.post('/api', async(req, res, next) => {
try {
const p1 = await controller(req, res, next, userID, product)
console.log(p1)
} catch (err) {
console.log(err)
}
})
controller.js
var x = async(req, res, next, userID, product) => {
let query = { uid: userID }
let update = { $push: { product: product }}
let options = {
safe: true,
new: true,
upsert: true
}
return Model.findOneAndUpdate(query, update, options).exec()
}
module.exports = x;