我对Sequelize和Promises并不陌生,对于不熟悉Java脚本语言和JavaScript语言的人来说,这可能会有些混乱。无论如何,我注意到在承诺的某些实现中使用了“返回”。在其他实现中则不是。 例如:
//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.`}))
};
有人可以向我解释“返回”的用法吗?由于第二个代码有效,因此显然没有必要吗?那么我什么时候必须使用它? 谢谢!!
答案 0 :(得分:0)
从技术上讲,您询问了箭头功能。
const dummyData = { foo: "lorem" };
const af1 = () => dummyData;
const af2 = () => {
dummyData.foo = "bar";
return dummyData;
};
const af3 = () => { foo: "bar" };
const af4 = () => ({
foo: "bar"
});
console.log(af1());
console.log(af2());
console.log(af3()); // Be aware if you wanna return something's started with bracket
console.log(af4());
如您所见,我们在return
中使用af1
语句,因为我们必须在返回值之前编写另一个“逻辑”。如果您不这样做,则可以避免使用return
语句(它可以提高代码的简洁性和可读性)。