我有下面这个 Sequelize Controller :
const Category = require('../models').category;
module.exports = {
list(req, res) {
return Category
.all({attributes: ['title']})
.then(categories => res.status(200).send(categories))
.catch(error => res.status(400).send(error));
}
};
本质上,返回 Category.all({attributes: ['title']})
会产生以下数组:
[
{"title": "video"},
{"title": "gif"},
{"title": "website"}
]
我想将对象 {"title": "all"}
添加到数组的开头,方法如下:
const Category = require('../models').category;
module.exports = {
list(req, res) {
return Category
.all({attributes: ['title']})
.then(categories =>
categories.unshift({"title": "all"})
res.status(200).send(categories)
)
.catch(error => res.status(400).send(error));
}
};
但我知道这并不完全正确。在处理 Promise 和 .then()
语句时,如何编辑 .then()
语句中的类别数组?谢谢!
最佳答案
.then(categories => {
categories.unshift({"title": "all"})
res.status(200).send(categories)
})
只需在 then 语句中的代码周围添加花括号,这样它就不是隐含的返回。
关于javascript - 在 Promise 中编辑 .then(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50263476/