【发布时间】:2018-12-28 12:56:33
【问题描述】:
我是 Sequelize 和 Promises 的新手,对于不太熟悉它们和 javaScript 语言的人来说,这可能会有点令人困惑。无论如何,我注意到在某些承诺的实现中,使用了“return”。在其他实现中不是。 例如:
//FILL JOIN TABLE FROM EXISTING DATA
Blog.find({where: {id: '1'}}) .then(blog => {
return Tag.find({where: {id: '1'}}).then(tag => {
return blog.hasTag(tag).
then(result => {
// result would be false BECAUSE the blog.addTag is still not used yet
console.log("3 RESULT IS"+ result);
return blog.addTag(tag).
then(() => {
return blog.hasTag(tag).
then(result => {
// result would be true
console.log("4 RESULT IS"+ result);
})
})
})
})
})
这里:它们没有被使用。
const tags = body.tags.map(tag => Tag.findOrCreate({ where: { name: tag }, defaults: { name: tag }})
.spread((tag, created) => tag))
User.findById(body.userId) //We will check if the user who wants to create the blog actually exists
.then(() => Blog.create(body))
.then(blog => Promise.all(tags).then(storedTags => blog.addTags(storedTags)).then(() => blog/*blog now is associated with stored tags*/)) //Associate the tags to the blog
.then(blog => Blog.findOne({ where: {id: blog.id}, include: [User, Tag]})) // We will find the blog we have just created and we will include the corresponding user and tags
.then(blogWithAssociations => res.json(blogWithAssociations)) // we will show it
.catch(err => res.status(400).json({ err: `User with id = [${body.userId}] doesn\'t exist.`}))
};
有人可以向我解释一下“return”的用法吗?显然没有必要,因为第二个代码有效?那么我什么时候必须使用它呢? 谢谢!!
【问题讨论】:
-
在这种
() => Blog.create(body)形式的箭头函数中,有一个隐含的返回 ...它本质上是() => { return Blog.create(body);}- 所以,这个问题实际上与续集无关或承诺,更多的是与javascript arrow function syntax as documented here -
哦,好的,谢谢你
标签: javascript database postgresql promise sequelize.js